To make your existing code work you\'ll also need to override has_post_thumbnail
:
add_filter( \'has_post_thumbnail\', \'__return_true\' );
since your theme is probably guarding get_the_post_thumbnail() with has_post_thumbnail(), so that now needs to return true in the default case.
However there\'s still a chance that this won\'t work, if the theme you\'re using goes directly to get_post_thumbnail_id()
. To make that work, you\'ll need to have an ID for your image: either
upload the image to the media library
pick an out-of-range ID, e.g. -123, to be the thumbnail attachment ID and then fake the image by hooking image_downsize
(I think!)
function image_downsize_default_thumbnail( $downsize, $id, $size )
{
if ( $id == -123 )
{
return array(
\'https://upload.wikimedia.org/wikipedia/commons/f/f9/Google_Lens_-_new_logo.png\',
1024, 1024, false );
}
return $downsize;
}
and then add a default_post_metadata
hook to fill in the missing thumbnail ID when absent, which is the postmeta key _thumbnail_id
:
function default_post_metadata__thumbnail_id( $value, $object_id, $meta_key,
$single, $meta_type )
{
if ( \'_thumbnail_id\' == $meta_key )
{
$value = -123; // the attachment ID for the default image
}
return $value;
}
add_filter( \'default_post_metadata\', \'default_post_metadata__thumbnail_id\', 10, 5 );
(We can ignore $single as get_metadata_default()
will wrap the value in an array if necessary, although get_post_thumbnail_id()
passes $single = true anyway.)
With this filter you shouldn\'t need to hook has_post_thumbnail and post_thumbnail_html, as it should pick up the default image as if it were the real thumbnail. You could look up the default ID from a post or from an option here too if you\'d prefer rather than hard-coding it.