[英]Attaching a thumbnail while using wp_insert_post() in WordPress
I have a script that creates posts using wp_insert_post(). 我有一个使用wp_insert_post()创建帖子的脚本。 Every day the script creates 12 posts, and the posts have the same names.
脚本每天都会创建12个帖子,并且这些帖子具有相同的名称。
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. 我在媒体库中拥有所有12张图像。
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 看看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: 因此,插入帖子后,对您已有的代码稍作更改,然后可以使用以下方法获取新帖子的ID:
$post_ID = wp_insert_post($post);
Then you can use that to add the image using set_post_thumbnail. 然后,您可以使用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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.