Automatic set a featured image from the first image’s url (or tag) in the article

You can display the first image from your post content as a but can’t set that as a featured image, but you can display it.

Create a function to find the first tag from the post content starting with <img> element using regex and echo the image where you wish to display the first image. In the below function we use ob_start() which creates a buffer which output is written to.

The below code has 2 options to fetch only specific extension or only the images. Un comment the code which you are willing to use the jpg extension image and comment the other output.

<?php
function prefix_get_first_image() {
  global $post, $posts;
  $first_image="";
  ob_start();
  ob_end_clean();
  //Regex to only fetch .JPG extension images
  //$output = preg_match_all( '/<img ([^>]* )?src=[\"\']([^\"\']*\.jpe?g)[\"\']/Ui', $post->post_content, $matches );

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

  // Define the default image if no img is inserted in the content
 if ( empty( $first_image ) ) {
    $first_image = get_template_directory_uri() . '/images/default-image.jpg';
  }
  return $first_image;
}
?>

Now where you want to display the image place the following function and echo it.

<?php echo prefix_get_first_image(); ?>

I’m not a master in WordPress but yes there might be a plugin to do that but I think you might be doing this as you may have many posts with those images inserted into the content already. But its a good idea to set the featured image from media library. You should use the WordPress Native functionality rather than using custom defined methods to force the native WordPress functions.

techhipbettruvabetnorabahisbahis forumuedusedueduseduseduedusedusedusedusedu