Reputation: 25
I'm struggling a bit to insert a post with the features I require.
include ('../wp-load.php');
$my_post = array(
'post_title' => 'title' ,
'post_content' => 'some content',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(34,35),
'tags_input' => array('tag1,tag2'),
'the_post_thumbnail' => 526
);
// Insert the post into the database
wp_insert_post( $my_post );
Question 1:
It's all working besides for 'the_post_thumbnail' => 526 - I was hoping that was going to attach the media item id (526) as the featured post image (obviously this isn't working). What is the correct way to do this?
Question 2:
Is there a way to get the URL of the post that is created?
Upvotes: 1
Views: 371
Reputation: 11378
Please try the following example that uses the functions set_post_thumbnail()
and get_permalink()
:
$my_post = array(
'post_title' => 'title' ,
'post_content' => 'some content',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(34,35),
'tags_input' => array('tag1,tag2'),
);
// Insert the post into the database
$pid = wp_insert_post( $my_post );
if( is_wp_error( $pid ) )
{
// Display error:
echo $pid->get_error_message();
}
else
{
// Set featured image to inserted post:
set_post_thumbnail( $pid, 526 );
// Get permalink:
$link = get_permalink( $pid );
}
where we use is_wp_error()
to make sure the insert was sucessful.
Hope this helps.
Upvotes: 2