I want to use a default image as a featured image for all those Posts and Pages, where is not any selected featured image from media. I have tried this code in function.php but not working,

function filter_post_thumbnail( $html ) {
    if ( '' == $html ) {
        return '<img src="https://upload.wikimedia.org/wikipedia/commons/f/f9/Google_Lens_-_new_logo.png" />';
    // Else, return the post thumbnail
    return $html;
add_filter( 'post_thumbnail_html', 'filter_post_thumbnail' );

Have any solution by implementing some piece of code in function.php file?

  • Did Rups response answer your question? I see you've not left any comments but you also haven't upvoted or accepted the answer
    – Tom J Nowell
    Sep 29, 2020 at 11:06

1 Answer 1


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

  1. upload the image to the media library

  2. 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(
                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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.