Support » Fixing WordPress » If the current post lacks a thumbnail use first Image in Post

  • I’m trying to do something I thought would be simple but I’m having a hard time putting it together. Here is what I want, use the new post_thumbnail feature if one is defined but if one is not defined use the first image in post. So far this is my code.

    <?php add_theme_support( 'post-thumbnails' );
    set_post_thumbnail_size( 120, 120, true ); // 120 pixels wide by 120 pixels tall, hard crop mode
    add_filter( 'post_thumbnail_html', 'my_post_image_html', 10, 3 );
    function my_post_image_html( $html, $post_id, $post_image_id ) {
    	$html = '<a href="' . get_permalink( $post_id ) . '" title="' . esc_attr( get_post_field( 'post_title', $post_id ) ) . '">' . $html . '</a>';
    	return $html;
    function catch_that_image() {
      global $post, $posts;
      $first_img = '';
      $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
      $first_img = $matches [1] [0];
      if(empty($first_img)){ //Defines a default image
        $first_img = "/images/default.jpg";
      return $first_img;

    and this is how I insert in my theme:

    if ( has_post_thumbnail() ) {
    	// the current post has a thumbnail
    } else {
    	// the current post lacks a thumbnail
    echo catch_that_image();

    If I define the thumbnail it works fine, otherwise it only returns the URL of the image and not the thumbnail itself. I know it has to do with the echo catch_that_image(); statement but I’m not sure what to do with it or how to get it into a img src=. Could someone help with this please. I also would like the images to link to the post. Thanks everyone

Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
  • The topic ‘If the current post lacks a thumbnail use first Image in Post’ is closed to new replies.