0

Is there a way or a plugin to set a featured image from the first image's url (or tag) posted in the article?

  • Thank you for the answers. I found a solution using QQWorld Auto Save Images plugin. The problem is that I would like to avoid the downloading process because due to the quantity of the images to download and store it is making the server slow... – Alessandro Carrese Oct 9 '17 at 15:20
0

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.

0

Try the below plugin for set first image in the content to feature.

https://wordpress.org/plugins/get-first-image-set-as-featured-image/
https://wordpress.org/plugins/quick-featured-images/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.