Bobcares

Set the featured image in WordPress Programmatically | How to

by | Jun 11, 2022

Set the featured image in WordPress Programmatically is as simple as it gets. We’re here to show you the simplest way.

Bobcares responds to all inquiries, no matter how big or small, as part of our WordPress support service.

Let’s take a look at how our Support team easily sets the featured image in WordPress programmatically.

Set the featured image in WordPress Programmatically

WordPress comes with a slew of useful website features built-in. The Featured Image is one of them. A featured image is an image that serves as a representation of a post, page, or custom post type. The post thumbnail can be set manually or programmatically. Let’s take a look at each option separately.

Set the Post Thumbnail manually

  • By going to the Set featured Image section, we can assign the featured image to specific posts or pages.set featured image wordpress programmatically
  • It will launch the WordPress media uploader, from which we can select an existing image or upload a new one.
  • Thus, setting the post thumbnail in WordPress is simple. Other posts, pages, and post types must follow the same steps.

Programmatically change the featured image

Create HTML Form

We require a form with file input and a submit button to add the featured image via coding. So, in the page template, paste the HTML below.

<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 shows a form with a file input field and a submit button.

set featured image wordpress programmatically

We can also include a hidden field with a nonce value. This nonce value is used to protect the form from malicious attacks and misuse. We’ll check this nonce value on the server side and only process the form if it’s valid.

Server-Side Code

It should now set a featured image when you click the submit button. So, in the active themes functions.php file, paste the following code.

 

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');

Before running any code, we must first verify a nonce value using the wp_verify_nonce() method. We used the following methods to create a post thumbnail.

  1. wp_upload_bits() : It creates a file with the specified content in the upload folder. The file will be placed in the current month’s folder automatically.
  2. wp_check_filetype() : From the file name, determine the file type.
  3. sanitize_file_name() : It replaces whitespaces in the file name with dashes.
  4. wp_insert_attachment() : This method creates a database entry for an attachment.
  5. wp_generate_attachment_metadata() : It creates metadata for the image, as well as thumbnails and other intermediate sizes. These dimensions are set in Settings => Media Screen.
  6. wp_update_attachment_metadata() : In the post meta_table, update the metadata.
  7. set_post_thumbnail() : The featured image for the current post is set.

Finally, we can give it a shot. We should see the post thumbnail under the Featured Image section if we go to the edit screen of a particular post. So this indicates that we were able to set the featured image in WordPress programmatically.

[Looking for a solution to another query? We are just a click away.]

Conclusion

To sum up, our Support team demonstrates how to programmatically set the featured image in WordPress.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

0 Comments

Submit a Comment

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

Never again lose customers to poor
server speed! Let us help you.