我有一个使用wp_insert_post()创建帖子的脚本。脚本每天创建12个帖子,帖子具有相同的名称。
这是使用的代码:
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;
}
我想要做的是让每个帖子自动附加媒体库中的缩略图(每次创建帖子时都不上传新图像)
我在媒体库中有12张图片
我的问题是我尝试的所有内容似乎都无法正常工作,或者尝试重新上传图片,这些图片会重复填充我的服务器。
任何人都可以了解我可以做什么?
答案 0 :(得分:0)
您可以使用以下功能设置帖子的缩略图:
set_post_thumbnail( $post, $thumbnail_id );
看一下WordPress codex
因此,在对您已经拥有的代码进行轻微更改后插入帖子后,您可以使用以下命令获取新帖子的ID:
$post_ID = wp_insert_post($post);
然后您可以使用它来使用set_post_thumbnail添加图像。
所以你的代码应该看起来像这样:
$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 );