How To Set Featured Image Programmatically In WordPress

Are you looking to set featured image using the code in WordPress? Sometimes, you came across a task where you need to write a piece of code which should set post thumbnail for a post, page, or custom post types. In this article, we study how to set featured image programmatically in WordPress.

WordPress provides a lot of useful features for websites. One of them is Featured Image aka Post Thumbnail. Featured Image is a representative image for post, page, or custom post type.

Regular Way to Set Post Thumbnail

We can upload featured images to specific posts or pages by clicking on the ‘Set featured Image’ link. It will open a WordPress media uploader where you can choose an existing image or upload the new image.

Set Featured Image

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

But as mentioned in the beginning, the purpose of this article is to write a code that set post thumbnail without following the above steps.

Set Featured Image Programmatically

For this tutorial, I am creating a form where a user can select an image and this image will set as post thumbnail to the specified post id. Place the below code in your template file.

<form method="post" enctype="multipart/form-data">
	<div class="form-group">
		<label><?php _e('Select Image:', 'Your text domain here');?></label>
		<input type="file" name="image">
	<div class="form-group">
		<input type="submit" name="upload_file" value="Submit">

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


Now, on the click of the submit button, we need to set a featured image. So write the code below in the active themes functions.php file.

function fn_set_featured_image() {
	if ( isset($_POST['upload_file']) ) {

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

		if ( ! $upload_file['error'] ) {
			$post_id = YOUR_POST_ID_HERE; //set post id to which you need to set 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 using a the wp_upload_bits() method which uploads the image and returns absolute and relative path. We have to take a generated absolute path and pass to the next methods like wp_check_filetype(), wp_insert_attachment(), and wp_generate_attachment_metadata() for additional processing.

After this, if you go the edit screen of a specified post you will see the post thumbnail under the Featured Image section. It means we successfully set the featured image programmatically.

Related Articles

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

7 thoughts on “How To Set Featured Image Programmatically In WordPress

  1. 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.

  2. 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 *