How to Automatically Set the Featured Image in WordPress

Home » Snippets » How to Automatically Set the Featured Image in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Are you tired of manually setting the featured image for each of your WordPress posts? Wish there was a way to automate this process and save yourself valuable time and effort? Well, you’re in luck. In this article, we’ll show you how to automatically set the featured image for your WordPress posts, so you can focus on creating great content without the hassle of manually selecting an image every time. Let’s dive in and streamline your workflow!

					function wpturbo_set_featured_image() {
    global $post;

    // Get all posts without a featured image
    $args = array(
        'post_type'      => 'post',
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'meta_query'     => array(
            array(
                'key'     => '_thumbnail_id',
                'compare' => 'NOT EXISTS',
            ),
        ),
    );

    $query = new WP_Query( $args );

    // Loop through each post and set a featured image
    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
            $query->the_post();

            // Get the first image attachment for the post
            $attachments = get_posts( array(
                'post_type'      => 'attachment',
                'posts_per_page' => 1,
                'post_parent'    => $post->ID,
                'orderby'        => 'menu_order',
                'order'          => 'ASC',
             ) );

            if ( $attachments ) {
                // Set the first image as the featured image
                set_post_thumbnail( $post->ID, $attachments[0]->ID );
            }
        }
        wp_reset_postdata();
    }
}

add_action( 'init', 'wpturbo_set_featured_image' );
				

The code snippet above allows you to automatically set a featured image for all posts that do not currently have one. This can be useful if you have a large number of posts and want to ensure that each one has a featured image for consistency or design purposes.

The function wpturbo_set_featured_image() is responsible for performing this task. It starts by using the global $post variable to access the currently processed post.

Next, it defines an array of arguments ($args) to query for all posts that do not have a featured image. This is done by setting the meta_query argument to look for posts where the _thumbnail_id meta key does not exist. This effectively filters out posts that already have a featured image attached.

The function then creates a new instance of WP_Query using the defined arguments and assigns it to the variable $query. This query will retrieve all the posts that match the specified criteria.

The code then checks if the query has any posts ($query->have_posts()), and if so, enters a loop to process each one. Inside the loop, the function uses the_post() to set up the global post variable for each post.

The next step is to retrieve the first image attachment for the post using get_posts(). This query specifies that it should retrieve attachments of the post type, limit the result to one attachment, and order them by menu order in ascending order. This ensures that the first attachment returned is the one that should be set as the featured image.

If there is at least one attachment found ($attachments), the function proceeds to set the first attachment as the featured image using set_post_thumbnail(). This function takes the post ID and the ID of the attachment to set as the featured image.

After the loop has processed all the posts, the function calls wp_reset_postdata() to reset the global post data.

Finally, the function is hooked to the init action using add_action(). This ensures that the wpturbo_set_featured_image() function is executed at the appropriate time during the WordPress initialization process.

By using this code snippet, you can automate the process of setting a featured image for all posts that do not currently have one, saving you time and effort in managing your WordPress site’s featured images.

Register an account to save your snippets or go Pro to get more features.