How to replace the_post_thumbnail template tag and show the first inside the post image instead

I want WordPress to return the first post image or a default image if no featured image has been set. My theme uses the_post_thumbnail many times, so I don’t want to go through and change all references to a new function. I’d rather filter the core. Here’s what I’ve added to functions.php:

add_filter('post_thumbnail_html', 'my_thumbnail_html', 10, 5);

function my_thumbnail_html( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
    global $post, $posts;
    if (has_post_thumbnail() ) {
        echo get_the_post_thumbnail( null, $size, $attr );
    }
    else {
        $first_img = '';
        ob_start();
        ob_end_clean();
        $output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
        $first_img = $matches [1] [0];
        if(empty($first_img)){
            $first_img = get_bloginfo("template_url") . '/images/default.gif';
        }
        return $first_img;
    }
}

How do I hook this correctly?

Related posts

Leave a Reply

2 comments

  1. Actually there isn’t the_post_thumbnail filter applied anywhere.

    The one you could try to use and to modify content that goes to the_post_thumbnail function is the post_thumbnail_html filter what is called with the following arguments $html, $post_id, $post_thumbnail_id, $size, $attr.

  2. Figured it out:

    function get_attachment_id_from_src( $image_src ) {
        global $wpdb;
        $query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$image_src'";
        $id = $wpdb->get_var($query);
        return $id;
    }
    
    add_filter( 'post_thumbnail_html', 'my_post_image_html', 10, 5 );
    
    function my_post_image_html( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
        if( '' == $html ) {
            global $post, $posts;
            ob_start();
            ob_end_clean();
            $output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
            $first_img = $matches [1] [0];
            if ( empty( $first_img ) ){
                $image_id = 129; // default image ID
            }
            else {
                $image_id = get_attachment_id_from_src($first_img);
            }
            $html = wp_get_attachment_image( $image_id, $size, false, $attr );
        }
        return $html;
    }