我正在使用中的函数this 回答上载、附加,然后[设置\\u post\\u tumbnail][2]/将特色图像添加到我通过RSS源创建的帖子。
我运行了一个测试,输出显示附件ID与我的缩略图ID匹配。我在媒体库中进行了检查,它正在根据get_post_thumbnail_id 但是the problem is 我的特色图像元框没有通过仪表板显示图像,或者在我的模板中使用[获取帖子缩略图][4]时也没有显示图像。
我在这里遗漏了什么步骤吗?代码主要来自上面链接的答案,最后还有一些测试。
global $wp_query;
wp_insert_post($my_post); // create a new post
$post_id = $wp_query->post->ID; // get the ID for the new post
$image_url = $thumbnail;
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if(wp_mkdir_p($upload_dir[\'path\']))
$file = $upload_dir[\'path\'] . \'/\' . $filename;
else
$file = $upload_dir[\'basedir\'] . \'/\' . $filename;
file_put_contents($file, $image_data);
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
\'post_mime_type\' => $wp_filetype[\'type\'],
\'post_title\' => sanitize_file_name($filename),
\'post_content\' => \'\',
\'post_status\' => \'inherit\'
);
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
require_once(ABSPATH . \'wp-admin/includes/image.php\');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );
echo "Attachment ID: " . $attach_id;
$post_thumbnail_id = get_post_thumbnail_id( $post_id );
echo "Thumbnail ID: " . $post_thumbnail_id;
get_the_post_thumbnail($post_id, \'full\');
最合适的回答,由SO网友:birgire 整理而成
而不是
wp_insert_post($my_post); // create a new post
$post_id = $wp_query->post->ID; // get the ID for the new post
尝试以下操作:
$post_id = wp_insert_post($my_post); // create a new post
获取插入的帖子ID。