最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin6PV0评论

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.

Post a comment

comment list (0)

  1. No comments so far