
Programmatically Set Featured Image for WordPress Posts and Pages using PHP.
Quick Summary of Contents
A few weeks ago, I received an email and comment from a reader searching for an easy method to create WordPress posts and pages using PHP programmatically.
The reader was successfully able to create a WordPress post and page using the tutorial, but shed light on another challenge when creating an automated post:
How does one set a featured image for a programmatically created post?
In this tutorial, I won’t dive deep into the details of the inner workings of creating a post. Again, there’s a previous tutorial for that. 😉
To level set, this tutorial will assist you in programmatically setting a featured image for a WordPress Post or Page using PHP based on the following:
- Not using native WordPress Set Feature for Post or Page Image functionality and user interface.
- No form submission or upload functionality.
- No post or page creation.
This tutorial strictly covers the following using PHP programming:
- uploading of a file to the WordPress Media Library with necessary attachment attributes and metadata.
- associating newly uploaded images to post as featured images.
Tutorial Pre-Requisites
Before you eagerly dive into the tutorial and its code, be sure you have the following prerequisites met as identified in the previous tutorial.
Without having met the prerequisites, today’s tutorial WILL NOT OPERATE. Nevertheless, let’s get started with today’s tutorial.
Accessing Built-In WordPress Functions.
For this tutorial, I’ve created a directory named “upd” within the root directory of my WordPress environment and have created a file named test.php.
One of the first things needed for this tutorial is the ability to access WordPress functions. To do so, you’ll need to require wp-load.php — loads and offers access to built-in WordPress functions — in test.php.
Defining Featured Image Variables and Image Existence.
Next, define and set the following variables to be used when uploading an image to WordPress Media Library and associating the image file to a WordPress post as a featured image:
- postID – set this value equal to a Post or Page id (integer)
- IMGFileName – set this value to be the entire file name, including the extension
- dirPath – leave set to PHP’s getcwd method, which returns the current file or directory path
- IMGFilePath – set to be the concatenation of dirPath and IMGFileName variables — full path of the image that is to be uploaded to WordPress Media Library
- message – this is the text message to be displayed should IMGFileName variable value not exist in the directory
<?php // require wp-load.php to use built-in WordPress functions require_once("../wp-load.php"); // WordPress Post ID for featured image to be set $postId = '5342'; // image to be uploaded to WordPress and set as featured image $IMGFileName = 'turkey.png'; // current path directory $dirPath = getcwd(); // full path of image $IMGFilePath = $dirPath.'/'.$IMGFileName; // error message for file not found in directory $message = $IMGFileName.' is not available or found in directory.'; ?>
Once the aforementioned variables are successfully defined with their respective values, it’s time to check and validate the specified image file to be set as the featured image exists in the same directory as test.php file.
To do so, use PHP’s file_exist method via an if statement, passing to it the IMGFileName variable as an argument.
If the image exists, then additional code will be executed, and the appropriate value for the message variable will be set within this code.
Also, don’t forget to echo the message variable. It’s used to communicate the humanly readable progress of script execution to the web browser.
<?php // does image file exist in directory if(file_exists($IMGFileName)){ // additional code here } echo $message; ?>
Uploading and Associating Images to WordPress Post or Page as the Featured Image.
Okay! Now it’s time to get down to the nitty-gritty details you’ve been waiting for — how to programmatically set featured images for WordPress Post or Page using PHP.
The next 60 or so lines of code needed to achieve this tutorial’s objective will occur within the if statement of the previous section.
Within this same section, the following built-in WordPress functions are used to set feature images to a given WordPress Post or Page:
- wp_upload_bits – creates a file in the upload directory
- wp_check_filetype – retrieves the file type from the filename
- sanitize_file_name – sanitizes a filename replacing whitespace with dashes
- wp_insert_attachment – inserts an attachment into the media library
- wp_generate_attachement_metadata – generates metadata for an image attachment
- set_post_thumbnail – sets a post thumbnail
Reviewing the list of functions above, one would assume there would be a wp_featured_image function of some sort. But no, it’s really the set_post_thumbnail that is the wp_featured_image equivalent.
Technically speaking, set_post_thumbnail is really all you need if the image already exists in your WordPress Media Library.
But remember, this tutorial is about how to programmatically upload images to WordPress Media Library.
With a bit more elbow grease, you could create your own upload form using PHP and then replace IMGFileName variable’s value with the respective file POST and FILE variables. 😉
For the sake of time, I won’t explain the code line by line but do read the comments in association with the function definitions above to get the gist of what’s going on throughout the code (see below).
Last but not least, we need to know whether the code is executed or not. Defining the success variable to be equal to set_post_thumbnail, create an if statement for the success variable.
If the desired WordPress Post or Page has a featured image successfully set, then set the message variable to indicate such messaging. Otherwise, the featured image has not been set.
And believe it or not, this is all needed for you to programmatically set a featured image for a WordPress Post or Page using PHP. Any questions or comments?
<?PHP //prepare upload image to WordPress Media Library $upload = wp_upload_bits($IMGFileName , null, file_get_contents($IMGFilePath, FILE_USE_INCLUDE_PATH)); // check and return file type $imageFile = $upload['file']; $wpFileType = wp_check_filetype($imageFile, null); // Attachment attributes for file $attachment = array( 'post_mime_type' => $wpFileType['type'], // file type 'post_title' => sanitize_file_name($imageFile), // sanitize and use image name as file name 'post_content' => '', // could use the image description here as the content 'post_status' => 'inherit' ); // insert and return attachment id $attachmentId = wp_insert_attachment( $attachment, $imageFile, $postId ); // insert and return attachment metadata $attachmentData = wp_generate_attachment_metadata( $attachmentId, $imageFile); // update and return attachment metadata wp_update_attachment_metadata( $attachmentId, $attachmentData ); // finally, associate attachment id to post id $success = set_post_thumbnail( $postId, $attachmentId ); // was featured image associated with post? if($success){ $message = $IMGFileName.' has been added as featured image to post.'; } else { $message = $IMGFileName.' has NOT been added as featured image to post.'; } ?>
Video: How To Programmatically Set A Featured Image
And for those of you that love WordPress video tutorials, watch and learn in this quick video how to programmatically set a featured image for a WordPress Post or Page using PHP. Enjoy! 😉
Entire Tutorial Codebase.
Copy, paste, and modify the code below, and you’re ready to test away. Good luck!
<?php // require wp-load.php to use built-in WordPress functions require_once("../wp-load.php"); // WordPress Post ID for featured image to be set $postId = '5342'; // image to be uploaded to WordPress and set as featured image $IMGFileName = 'turkey.png'; // current path directory $dirPath = getcwd(); // full path of image $IMGFilePath = $dirPath.'/'.$IMGFileName; // error message for file not found in directory $message = $IMGFileName.' is not available or found in directory.'; // does image file exist in directory if(file_exists($IMGFileName)){ //prepare upload image to WordPress Media Library $upload = wp_upload_bits($IMGFileName , null, file_get_contents($IMGFilePath, FILE_USE_INCLUDE_PATH)); // check and return file type $imageFile = $upload['file']; $wpFileType = wp_check_filetype($imageFile, null); // Attachment attributes for file $attachment = array( 'post_mime_type' => $wpFileType['type'], // file type 'post_title' => sanitize_file_name($imageFile), // sanitize and use image name as file name 'post_content' => '', // could use the image description here as the content 'post_status' => 'inherit' ); // insert and return attachment id $attachmentId = wp_insert_attachment( $attachment, $imageFile, $postId ); // insert and return attachment metadata $attachmentData = wp_generate_attachment_metadata( $attachmentId, $imageFile); // update and return attachment metadata wp_update_attachment_metadata( $attachmentId, $attachmentData ); // finally, associate attachment id to post id $success = set_post_thumbnail( $postId, $attachmentId ); // was featured image associated with post? if($success){ $message = $IMGFileName.' has been added as featured image to post.'; } else { $message = $IMGFileName.' has NOT been added as featured image to post.'; } } echo $message; ?>
Sir, Can you tell me how i can implement it in a new post without a post id and using an url as an image?
Thanks
Hi, I’ve actually wrote about how to create a WordPress post using automated code. As for the url as an image, I’m not certain that I understand what you mean exactly. If you’re hoping to use a url, I’m not certain if that’s a possibility. Hope this helps.
Hi, how can I update image by json link array? my all post data come form json link.
Hi Harsh – What does your json data look like structure wise?
Hi.
The tutorial has helped me a lot!!
I am in the last step. I am working for a website “Secondwebsite” that is in a subdomain themainwebsite.com/thesecondwebsite.
I have a question, the code works for me 100% except when the images come from “themainwebsite” (and in my case all the images comes from there). I even receive the success message, but when I go to the post, the picture has not been attached (I see an empty thumbnail space) and when I go to /uploads/ I see the picture imported, but filesize = 0.
Thank you a lot!
Hi there! Glad the tutorial has helped you. 🙂 What are the file permissions of the folders involved?
Thanks for great post @Mr. Alvin Brown.