admin管理员组

文章数量:1291811

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.

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.

Share Improve this question asked Jun 4, 2021 at 2:46 ChandraChandra 232 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

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/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 );

本文标签: post thumbnailsSetting fallback (default) image to featured image block