Print Friendly and PDF

So this the last (perhaps) continuation of the posts getting the source URL of the featured image and using TimThumb with WordPress MultiSite. As the title says, today we are going to discuss how to automatically fetch the URL of the first image for any WordPress posts or pages and then we shall also see how to pass it to timthumb etc for creating thumbnails. This becomes useful, when your theme/plugin users are not using the featured image thingy of WordPress. In that scenario, what we can do is, search the post content for the any instance of image and return the first found image SRC. In case no images were found, we can also return some default image if necessary. So, let us see what we can do.

#1: Understanding the concept:

The concept remains the same as our previous post on getting the image SRC of featured image.

  • We search the post content using preg_match.
  • If any instance is found we return the src.
  • Else we return false or optionally return the default image URL

#2: The code behind:

/**
 * Auto Generate Thumbnail URL from the post content
 *
 * First checks if the featured image is present on the post/page or not
 * If yes, then it returns the featured image URL (Source URL)
 * else, it manually searches the content and returns the URL of the first image found
 *
 * If no image is found then it returns the $default variable which is set to false by default
 *
 * @uses itg_get_the_post_thumbnail_url
 * @param int $id Use null if within the loop or give some ID
 * @param string $size The size of the thumbnail, 'post-thumbnail' by default
 * @param bool|string $default The default URL of not-found image or boolean false which will be returned
 * @param string $type The type of the entry. Can be 'post' or 'page'
 * @return mixed bool|string The URL of the featured image or first found image on success, false or default image (as passed by the $default parameter) URL on failure
 */
function itg_auto_gen_thumbnail($id = null, $size = 'post-thumbnail', $default = false, $type = 'post') {
    /**
     * try to get the featured image URL
     * @see http://www.intechgrity.com/how-to-get-the-souce-url-of-the-featured-image-in-wordpress/
     */
    $image_src = itg_get_the_post_thumbnail_url($id, $size);
    if($image_src != '') {
        //on success return the featured image
        return $image_src;
    } else {
        //try to get the first image
        if($id == null) {
            //called within the loop
            $content = get_the_content();
        } else {
            //get the post content
            $p_data = ($type == 'post')? get_post($id) : get_page($id);
            $content = $p_data->post_content;
            unset($p_data);
        }
        //the match pattern
        $src_pattern = '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i';
        //store $default to $src for returning
        $src = $default;
        $matches = array();

        //match it
        if(preg_match($src_pattern, $content, $matches)) {
            //found, so replace the $src value
            $src = trim($matches[1]);
        }

        return $src;
    }
}

So it is pretty much straight forward. It tries to get the featured image first. If not found then, it searches the content for an image. You call it like this:

//within loop
echo itg_auto_gen_thumbnail();

//within loop for different size
$my_image = itg_auto_gen_thumbnail(null, 'full');

//outside loop for a page
$my_image = itg_auto_gen_thumbnail(10, 'full', false, 'page');

//set default image SRC to return
$my_image = itg_auto_gen_thumbnail(null, 'full', 'http://locati.on/to/image.png');

As you can see, it uses the itg_get_the_post_thumbnail_url function internally. Have a look at here for more information. You can even pass the return image to TimThumb using our TimThumb compatibility function for dynamic resizing.

That will be all. Hope it helps you out for your code. If you have any question, then do ask.

has written 246 posts

Hey there! This is the place where I write about the technology I understand. Personally I'm a geek and professionally Web Developer. You can also check my other site to get to know about my other hobbies ;)

Swashata has another home at http://www.swashata.com/

Comments Feed

TOP

9 Responses

Comment Now

  1. Where do I put the code?

    • In your theme’s functions.php file put the functions. Now, where you need the image call the function. It can be the index.php or archive.php where you would like to show images with excerpt etc.

  2. I’m a bit confused. I don’t use Multisite, I just have one install of WordPress and I use Timthumb as well, but I would like for the image to set automatically upon uploading rather than me having to assign the image URL in Custom Fields. This can save me a lot of time since I just started using Timthumb on my Index page and having to go through now to set the URL for the image on all posts is an issue. How can I make this happen?

  3. how to make this work with a gallery in the post?

  4. I want to modify posts that don’t have a featured image, and add one. I’ve found that the all images are referenced in the posts table, and the featured image appears in postmeta, with a meta_key of ‘_thumbnail_id’.

    How would I go about modifying your work here in order to add the first image within a post to the postmeta table, so that it’s referred to as the featured image in the good old fashioned way?

    Thanks!

    • Update: I figured it out myself.
      In your Mysql database, run the following query (I did this via PHPMyAdmin):

      INSERT into
      `wp_postmeta` (post_id, meta_key, meta_value)

      SELECT
      ID,
      ‘_thumbnail_id’,
      SUBSTRING(`post_content` FROM locate(‘wp-image-’,`post_content`)+9 FOR
      locate(‘”‘,`post_content`,locate(‘wp-image-’,`post_content`))-(locate(‘wp-image-’,`post_content`)+9)
      ) as ‘first_image_id’

      FROM `wp_posts`
      where post_Status = ‘publish’
      and SUBSTRING(`post_content` FROM locate(‘wp-image-’,`post_content`)+9 FOR
      locate(‘”‘,`post_content`,locate(‘wp-image-’,`post_content`))-(locate(‘wp-image-’,`post_content`)+9)
      ) ”
      and ID not in
      (
      select ID from `wp_posts` inner join `wp_postmeta` on (`wp_posts`.ID = `wp_postmeta`.post_id)
      where meta_key = ‘_thumbnail_id’
      )

      This works only under the assumption that your image was generated in the post automatically by WordPress, and thus has a class of “wp-image-0000″, where the number is the ID of the image in the ‘posts’ table.

      I’d be happy for your opinion on this.

      -Ethan

Leave a Reply

Trackbacks/Pingbacks

Trackback URL

No trackbacks yet! If you wish, you can trackback this post from the above link