Creating WordPress Featured Images Programmatically

If you ever find yourself in a situation where you need to create a featured image for posts in WordPress programmatically (i.e. you’ve botched a migration to another host), I’ve got the solution for you.

First, add the ever-so-handy catch_that_image() function to your functions.php file:

function catch_that_image() {

     global $post, $posts;

     $first_img = '';

     ob_start();

     ob_end_clean();

     $output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);

     $first_img = $matches [1] [0];

     if(empty($first_img)){ //Defines a default image

          $first_img = "https://www.digital.ink/wp-content/uploads/dgtlnk-logo.svg";

     }

     return $first_img;

}

This handy function returns the first image in a post as a variable with which you can do as you please and should be in the metaphorical quiver of any WordPress developer.

Next, add the following lines of code to your single.php (or equivalent single post template file):

$mainimageURL= catch_that_image();
								
								
$desc = get_the_title();
								
$image = media_sideload_image( $mainimageURL, $the_id, $desc, 'id' );
							
set_post_thumbnail( $the_id, $image );


On page load of a single blog post, this code grabs the first image in the blog post, gets the title of the blog post and sets the featured image of the post to the first image with the post’s title as the image description.

Questions? Comments? Concerns?