Setting fallback (default) image to featured image block

The question:

I was trying to make a block based theme and encountered a problem trying to set a default featured image in case some posts do not have them.

Basically, we used to do this in php

<?php if ( has_post_thumbnail() ) {
} else { ?>
<img src="<?php bloginfo('template_directory'); ?>/images/default-image.jpg" alt="<?php the_title(); ?>" />
<?php } ?>

But now with blocks, themes are html and all I can see is

<!-- wp:post-featured-image {"isLink":true} /-->

I couldn’t find any other parameters here nor an if/else block so I could just add a plain html.

If anyone has done this, that would be of great help.


The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

I don’t know if you’re still looking for a solution, but you can use the post_thumbnail_html filter in you php file to return a fallback; like so.

 * Set the default image if none exists.
 * @param string $html              The post thumbnail HTML.
 * @param int    $post_id           The post ID.
 * @param int    $post_thumbnail_id The post thumbnail ID.
 * @return html
public function wp_893874_fallback_post_thumbnail_html( $html, $post_id, $post_thumbnail_id ) {
    if ( empty( $html ) ) {
        $html = '<img src="" width="400" height="200" loading="lazy" alt="' . get_the_title( $post_id ) . '" />';

    return $html;
add_filter( 'post_thumbnail_html', 'wp_893874_fallback_post_thumbnail_html', 5, 3 );

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment