Set the Featured Image Automatically
When a post is saved without a featured image, uses the first image attached to it or the first image block in its content.
Opens WPIDE on
Code
add_action( 'save_post', function ( $post_id, $post ) {
if ( wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) || 'auto-draft' === $post->post_status ) {
return;
}
if ( ! post_type_supports( $post->post_type, 'thumbnail' ) || has_post_thumbnail( $post_id ) ) {
return;
}
if ( preg_match( '/wp-image-(\d+)/', $post->post_content, $match ) && wp_attachment_is_image( (int) $match[1] ) ) {
set_post_thumbnail( $post_id, (int) $match[1] );
return;
}
$images = get_attached_media( 'image', $post_id );
if ( $images ) {
$first = reset( $images );
set_post_thumbnail( $post_id, $first->ID );
}
}, 10, 2 );
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.