Need to insert custom post type objects from code. Haven’t been able to add using the default method
$id = wp_insert_post(array('post_title'=>'random', 'post_type'=>'custom_post'));
creates a regular post instead.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
wp_insert_post() will fill out a default list of these but the
user is required to provide the title and content otherwise the
database write will fail.
$id = wp_insert_post(array( 'post_title'=>'random', 'post_type'=>'custom_post', 'post_content'=>'demo text' ));
Method 2
It can be done using the following code :-
To enter a new post for a custom type
$post_id = wp_insert_post(array ( 'post_type' => 'your_post_type', 'post_title' => $your_title, 'post_content' => $your_content, 'post_status' => 'publish', 'comment_status' => 'closed', // if you prefer 'ping_status' => 'closed', // if you prefer ));
After inserting the post, a post id will be returned by the above function. Now if you want to enter any post meta information w.r.t this post then following code snippet can be used.
if ($post_id) {
// insert post meta
add_post_meta($post_id, '_your_custom_1', $custom1);
add_post_meta($post_id, '_your_custom_2', $custom2);
add_post_meta($post_id, '_your_custom_3', $custom3);
}
Method 3
This example worked for me using meta_input
$post_id = wp_insert_post(array (
'post_type' => 'your_post_type',
'post_title' => $your_title,
'post_content' => $your_content,
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed',
'meta_input' => array(
'_your_custom_1' => $custom_1,
'_your_custom_2' => $custom_2,
'_your_custom_3' => $custom_3,
),
));
Method 4
I found using isset() allowed me to use wp_insert_post() on custom post types:
if ( !isset( $id ) ) {
$id = wp_insert_post( $new, true );
}
Method 5
I had the same problem. I tried every solution provided in most of the forums. But the actual solution that worked for me was the post type was the length of post_type.
The post_type length is limited to 20 characters. So anyone who has a similar issue try this if anything else didn’t work.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0