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?
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 thepost_thumbnail_html
filter what is called with the following arguments$html, $post_id, $post_thumbnail_id, $size, $attr
.Figured it out: