Web Blog | Blog, Design, Create, cssOrigins.com

Automatically Retrieve The First Image From Posts On Your Home Page

I found this particularly interesting, because I use a similar method to list images on the home page of my site as well. over the weekend if time allows I’ll be reviewing and adjusting my code. Hopefully this method will allow me to more easily display my post pictures where I need them. Thank you Smashing Magazine for posting.


Automatically Retrieve The First Image From Posts On Your Home Page

The problem . Many WordPress users use custom fields to display a thumbnail on their blog home page. Of course, this is a nice solution, but how about automatically retrieving the first image from a post and using it as a thumbnail?

The solution . This hack is quite easy to implement:

  1. Open the functions.php file in your theme.
  2. Paste this code in. Don’t forget to specify a default image on line 10 in case a post of yours does not have an image.function catch_that_image {
    global $post, $posts;
    $first_img = ”;
    ob_start;
    ob_end_clean;
    $output = preg_match_all’//i’, $post->post_content, $matches;
    $first_img = $matches [1] [0];
    ifempty$first_img{ //Defines a default image
    $first_img = "/images/default.jpg";
    }
    return $first_img;
  3. Save the functions.php file.
  4. On your blog home page index.php, call the function this way to get the URL of the first image from the post:

<?php echo catch_that_image() ?>

Code explanation . The function uses the global variable $post to parse the post’s content with a regular expression. If an image is found, its URL is returned by the function. If not, the default image URL is returned.

via 10 Exceptional WordPress Hacks | Developer’s Toolbox | Smashing Magazine .

Tags: , , , , , , , ,

Comments are closed.