Setting fallback (default) image to featured image block

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() ) {
the_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.

Thanks.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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="http://lorempixel.com/g/400/200" 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 stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x