How to Set Featured Image Programmatically in WordPress

Are you looking to programmatically set the featured image aka post thumbnail in WordPress? Sometimes, you need to write a script that should set a thumbnail for a post, page, or custom post type. In this article, we study how to set the featured image programmatically in WordPress.

WordPress comes with numerous useful built-in features. One of them is the Featured Image. A Featured Image is a representative image for a post, page, or custom post type. This image helps to recognize what the content is about.

In WordPress, one can set the post thumbnail either manually or programmatically. Let’s see both options one by one.

Manually Set the Post Thumbnail

We can assign the featured image to specific posts or pages by clicking on the Set featured Image section. It opens a WordPress media uploader where you either choose an existing image or upload a new one.

Set-Featured-Image

It is a straightforward way to set the post thumbnail in WordPress. The same steps have to follow for other posts, pages, and post types.

Set the Featured Image Programmatically

Create HTML Form

Setting the featured image via code requires the HTML form with file input and a submit button. Add the below HTML to your page template.

<form method="post" enctype="multipart/form-data">
    <p>
        <label>Select Image:</label>
        <input type="file" name="image" required />
    </p>
    <input type="hidden" name="image_nonce" value="<?php echo wp_create_nonce('image_nonce'); ?>" />
    <input type="submit" name="upload_file" value="Submit" />
</form>

This code will display the form with file input and the submit button.

Form

If you noticed, I have added the hidden field for a nonce. This nonce helps to protect the form against certain types of misuse, and malicious attacks. We’ll verify this nonce on the server side and process the form only if the nonce is valid.

Server-Side Code

Now, when the user clicks the submit button, it should set a featured image. For this, write the code below in the active themes functions.php file.

function fn_set_featured_image() {
    if ( isset( $_POST['upload_file'] ) && wp_verify_nonce( $_REQUEST['image_nonce'], 'image_nonce' ) ) {

        $upload = wp_upload_bits( $_FILES["image"]["name"], null, file_get_contents( $_FILES["image"]["tmp_name"] ) );

        if ( ! $upload['error'] ) {
            $post_id = 'POST_ID_HERE'; //set post id to which you need to add featured image
            $filename = $upload['file'];
            $wp_filetype = wp_check_filetype( $filename, null );
            $attachment = array(
                'post_mime_type' => $wp_filetype['type'],
                'post_title' => sanitize_file_name( $filename ),
                'post_content' => '',
                'post_status' => 'inherit'
            );

            $attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );

            if ( ! is_wp_error( $attachment_id ) ) {
                require_once(ABSPATH . 'wp-admin/includes/image.php');

                $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
                wp_update_attachment_metadata( $attachment_id, $attachment_data );
                set_post_thumbnail( $post_id, $attachment_id );
            }
        }
    }
}
add_action('init', 'fn_set_featured_image');

Here, I am first verifying a nonce using the wp_verify_nonce() method before executing a code.

For setting a post thumbnail I have used a few methods as follows.

  • wp_upload_bits() : It creates a file in the wp-content/upload folder with the given content. The file will be created automatically in the current month folder.
  • wp_check_filetype() : Retrieve a file type from the file name.
  • sanitize_file_name() : It replaces whitespaces with dashes in the file name.
  • wp_insert_attachment() : This method inserts an attachment entry into the database.
  • wp_generate_attachment_metadata() : It generates metadata of the image along with a thumbnail and other intermediate sizes of the image. These sizes are defined under Settings => Media Screen.
  • wp_update_attachment_metadata() : Update the metadata in the post_meta table.
  • set_post_thumbnail() : Sets the featured image for the given post.

Go ahead and give it a try. To verify whether the code works or not, go to the edit screen of a specified post and you should see the thumbnail under the Featured Image section. It means you have successfully set the featured image programmatically.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

12 thoughts on “How to Set Featured Image Programmatically in WordPress

  1. I have a site with a lot of old posts who’s featured image was previously populated from a custom field. Would it be possible to programmatically set the featured image for these posts from the url on the custom field?

    the wp_postmeta contains the image url in the meta_value for meta_value = ‘image’

  2. More usable with a plugin that works and is able to take first image and or a selected product image in each category and set it as category image in Woocommerce.

    Those i tried so far doesn’t work.

  3. I am using two websites.One for content writing (source website) and other for publishing (target website).
    I set featured image for one post A on source and write function to publish the post A on target.I fetch post A data from source wp_posts,wp_postmeta and insert the same into destination wp_posts,wp_postmeta.And also call the function set_post_thumbnails() to set featured image.It gets inserted and target website displays the post with feature image on front-end.When I Open target website admin panel and edit the post,I am unable to see the featured image for the same.Instead it shows default image.The image present in the source upload and target uploads folder.When i inspect the path of image,its name changes from image_name.jpg to image_name-696×198.jpg.Any solution or work around for this problem?Thank you in advance.

    1. It should see at the back-end. Not sure what’s going wrong on your site. Maybe some plugins or code are conflicting. I need more details. I can’t give a solution without seeing what plugins or which theme you are using.

Leave a Reply

Your email address will not be published. Required fields are marked *