php - How to programmatically set existing image in media library the featured image for a post in wordpress

I have uploaded some images to the wordpress media library. Now I am going to create some posts using php and want to us

I have uploaded some images to the wordpress media library. Now I am going to create some posts using php and want to use those already uploaded images as featured image for these posts respectively. How to set image as featured image for a post. I have tried below code. but it sets an empty image as featured image to posts.

function set_featured_image($post_id, $image_url){
global $wpdb;
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); 
$image_attachment_id = $attachment[0];
$attachment = array(
    'ID' => $image_attachment_id,
    'post_parent' => $post_id
);

$attachement_id = wp_insert_attachment( $attachment );
set_post_thumbnail( $post_id, $attachement_id ); // also tried using $image_attachment_id but same issue 

I got this blank featured image

Prior thanks to any help.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745625407a4636773.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信