I have a script that creates posts using wp_insert_post(). Every day the script creates 12 posts, and the posts have the same names.
This is the code used:
require_once( ABSPATH . 'wp-admin/includes/post.php' );
global $post;
function PostCreator($title, $name, $content, $sign, $meta_input) {
//$postID = post_exists( $title );
$post_data = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_type' => 'post',
'post_author' => '1',
'post_category' => array('category' => 2),
'meta_input' => $meta_input,
'post_name' => $name,
);
wp_insert_post( $post_data, $error_obj );
if(!isset($post))
add_action('admin_init', 'hbt_create_post' );
return $error_obj;
}
What I want to do is have each post automatically attach an thumbnail from the media library (not upload a new image every time a post is created)
I have all 12 images in the media library.
My problem is everything I try seems to either not work, or try to re-upload images, which fills my server with duplicates.
Anyone have any insight as to what I might be able to do?
You can set the thumbnail for a post with the following function:
set_post_thumbnail( $post, $thumbnail_id );
Take a look at the WordPress codex
So after inserting the post with a slight change to the code you have already, you can then grab the ID of the new post with:
$post_ID = wp_insert_post($post);
Then you can use that to add the image using set_post_thumbnail.
So your code should look something like this overall:
$post_data = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'publish',
'post_type' => 'post',
'post_author' => '1',
'post_category' => array('category' => 2),
'meta_input' => $meta_input,
'post_name' => $name,
);
$post_ID = wp_insert_post( $post_data, $error_obj );
$thumbnail_id = {your image id from media library};
set_post_thumbnail( $post_ID, $thumbnail_id );