I have tried every solution from similar answers and nothing seems to work on Wordpress 5.0 +
When saving a post I want to set its featured image to the first image in the post content.
function auto_set_featured( $post_id, $post, $update ) {
$images = get_posts( array(
'post_parent' => $post_id,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'posts_per_page' => 1
) );
set_post_thumbnail( $post_id, $images[0]->ID );
}
add_action( 'save_post', 'auto_set_featured', 10, 3);
In set_post_thumbnail()
if I set the image id manually it works but it does not seem to pick up $images[0]->ID
I'm not sure why this doesn't work.
Note: I'm testing on posts which have multiple images in the content so $images
should be returning an array. I also tried using $post->ID
and get_the_ID()
in the query and it does not work. I also tried adding the post ID manually for post_parent
.
var_dump($images)
beforeset_post_thumbnail
and see what you get.array(0) { }
so i'm not sure why it is not returning any images. The query seems correct.