Wood Chen

Wordpress: Automatically Set a Post's First Image as the Featured Image (Must Be in the Media Library), or Use a Specified Fallback

0 comments91 views0 words

This post was translated from Chinese by AI. If anything reads oddly, the Chinese original is authoritative. 中文原文

//Automatically set the first image in the post as the featured image; otherwise, use the specified logo image
function wpforce_featured() {
    global $post;
    $already_has_thumb = has_post_thumbnail($post->ID);
    if (!$already_has_thumb)  {
        $attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
        if ($attached_image) {
            foreach ($attached_image as $attachment_id => $attachment) {
                set_post_thumbnail($post->ID, $attachment_id);
            }
        } else {
            set_post_thumbnail($post->ID, '指定图片的ID');
        }
    }
}  //end function
add_action('the_post', 'wpforce_featured');
add_action('save_post', 'wpforce_featured');
add_action('draft_to_publish', 'wpforce_featured');
add_action('new_to_publish', 'wpforce_featured');
add_action('pending_to_publish', 'wpforce_featured');
add_action('future_to_publish', 'wpforce_featured');

Last updated 2024-01-14

Related posts

Comments 0