I am using this big theme that is almost entirely relying on widgets and sliders.
Now I trying to avoid looking for post_thumbnail
output code in all the included files in order to achieve fallback which should then grab first image in post or at last display default image.
Is there a way of controlling this via functions
file?
Any help appreciated.
Solution based on post_thumbnail_html
filter hook
doesn't display featured image if it is not explicitly set:
add_filter( 'post_thumbnail_html', 'my_post_thumbnail_fallback', 20, 5 );
function my_post_thumbnail_fallback( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
if ( empty( $html ) ) {
$image = get_children( "post_parent={$post_id}&post_type=attachment&post_mime_type=image&numberposts=1" );
if($image){
foreach ($image as $attachment_id => $attachment) {
$src = wp_get_attachment_image_src($attachment_id);
return printf(
'<img src="%s" height="%s" width="%s" />'
,$src[0]
,get_option( 'thumbnail_size_w' )
,get_option( 'thumbnail_size_h' )
);
}
}
else {
return printf(
'<img src="%s" height="%s" width="%s" />'
,get_template_directory_uri().'/images/featured/featured.jpg'
,get_option( 'thumbnail_size_w' )
,get_option( 'thumbnail_size_h' )
);
}
}
return $html;
}
Another solution that I found in this article and it's based on different action hooks
does thing as intended which displays(sets) first attachment image in post as featured or in last case scenario displays(sets) default image as post's featured image:
function autoset_featured() {
global $post;
$already_has_thumb = has_post_thumbnail($post->ID);
if (!$already_has_thumb) {
$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
if ($attached_image) {
foreach ($attached_image as $attachment_id => $attachment) {
set_post_thumbnail($post->ID, $attachment_id);
}
} else {
set_post_thumbnail($post->ID, '414');
}
}
} //end function
add_action('the_post', 'autoset_featured');
add_action('save_post', 'autoset_featured');
add_action('draft_to_publish', 'autoset_featured');
add_action('new_to_publish', 'autoset_featured');
add_action('pending_to_publish', 'autoset_featured');
add_action('future_to_publish', 'autoset_featured');
Now.. I do like that post_thumbnail_html
filter hook
solution and am intrigued by it not working.
Any help appreciated.