Set First Image In WordPress Post As The Featured Image

Add the following code to your functions.php file.

To run it, simply visit any page on the site – DO NOT USE THIS CODE ON YOUR LIVE SITE! Any visitor that visits any page will trigger this code. This code was created to manipulate content on a development site before it was merged with the live site



/** Function to set the first image as featured **/
function set_first_image_as_featured() 
{
/** Set the post arguments, here we're targetting all posts in the
	To go through all posts 
**/
  $args = array(
    'post_type' => 'post',
	'category_name' => 'articles',
    'numberposts' => -1, // Modify this to limit the number of posts if needed
  );

  $posts = get_posts($args);

/** Force include image files so that we can download and
    save the images locally  
**/
if(!function_exists('wp_get_current_user')) {
include(ABSPATH . "wp-includes/pluggable.php"); 
}
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');

/** Loop through all posts **/

  foreach ($posts as $post) {
  /** Only run if we don't already have a thmbnail image set **/
 if (!has_post_thumbnail($post->ID)) 
 { 

    $content = get_post_field('post_content', $post->ID);
	$alttext = get_post_field('post_title', $post->ID);
	/** Check we have post content to check **/
	if($content!='')
	{
	
	$doc = new DOMDocument();
    @$doc->loadHTML($content);
	/** Grab All Image Elements in the DOM. You can change 'img' to any
	    HTML tag such as 'p', 'iframe' etc - amend the following code
             according to your needs
	**/
    $images = $doc->getElementsByTagName('img');
	
	/** Check to make sure we have at least one image in the post **/
    if ($images->length > 0) 
	{
		/** Get the URL of the first image **/
      $first_image_url = $images->item(0)->getAttribute('src');
	  
     /** Check if image URL starts with an external domain (not your own website)**/
     if (strpos($first_image_url, get_home_url()) === false) {
		
        /** WARNING: Downloading from external sources can have copyright and security risks.**/
		
		/** Add the image to the WordPress Media Library and grab the id of the insered image
		    So we can assign it as the post thumbnail later
		**/
        $featured_image_id = media_sideload_image($first_image_url, $post->ID, $alttext, 'id');
	   
		/** Check whether we have a valid image id so we can attach it to the post **/
        if (!is_wp_error($featured_image_id)) 
		{
			/** Set the post thumbnail with the first image in the post **/
			set_post_thumbnail($post->ID, $featured_image_id);
			
			/** Remove the image from the post content and save the amended content
				Comment Out the line below if you want to keep the image in the post
			**/
			update_post_content_with_image_removed($post->ID, $first_image_url);
			
			/** Uncomment the following line for visual confirmation of items updated **/
			//echo 'done '.$post->ID.' IMG ID '.$featured_image_id. ' IMG - '.$first_image_url.' ALT - '.$alttext.'<br>';
        } // End Set post thumb
		
      } // END External Image Check
    } // END Has in post image
  }// End has Content
}// END Has Thumbnail
} // END Post Loop

} // End function

/** Run the function after WordPress is loaded **/
add_action('init', 'set_first_image_as_featured');

function update_post_content_with_image_removed($post_id, $image_url) 
{
  // 1. Fetch the existing post content
  $existing_content = get_post_field('post_content', $post_id);

  // 2. Escape the image URL for safe use in string replacement
  $escaped_url = str_replace('/', '\\/', $image_url);

  // 3. Remove the '<img>' tag with the specified URL using regular expressions
  // This approach is more flexible than str_replace for potential variations in the tag
  $updated_content = preg_replace('/<img[^>]*?src="' . $escaped_url . '"[^>]*?>/i', '', $existing_content);
  
  // 4. Update the post content in the database
  $args = array(
    'ID' => $post_id,
    'post_content' => $updated_content,
  );

	// Update the post with the revised content
		wp_update_post($args);
  
} // END update_post_content_with_image_removed

Disclaimer: The code on this website is provided "as is" and comes with no warranty. The author of this website does not accept any responsibility for issues arising from the use of code on this website. Before making any significant changes, ensure you take a backup of all files and do not work directly on a live/production website without thoughly testing your changes first.

Leave a Reply

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