echo 语句中的 WP 回退图像

WP fallback image in echo statement

我正在回复一些 HTML 相关帖子小部件。我想显示缩略图 ('get_the_post_thumbnail')(如果有),如果没有则显示后备。我不知道我是否应该在 var 中使用 if/else 语句(无法让它工作)或者最好的方法是什么。

这是我的回显代码:

echo '<div class="l-four"><div class="l-twelve l-mb1 recentThumb t-center">' . get_the_post_thumbnail($recent["ID"], 'thumbnail') .'</div><div class="l-twelve f-size14 f-l-height16 t-center"><a href="' . get_permalink($recent["ID"]) . '" class="c-gold">' . $recent["post_title"] .'</a></div></div>';

我试过在 var:

中使用 if/else
if ( has_post_thumbnail() ) {
    $img = get_the_post_thumbnail( $recent["ID"] );
} else {
    $img = '<img src="path/to/image" />';
}

并回应:

echo '<div class="l-four"><div class="l-twelve l-mb1 recentThumb t-center">' . $img .'</div><div class="l-twelve f-size14 f-l-height16 t-center"><a href="' . get_permalink($recent["ID"]) . '" class="c-gold">' . $recent["post_title"] .'</a></div></div>';

但它只是默认使用 else 语句,而不是从有它的文章中获取缩略图。

整个代码块

<?php 
    if ( has_post_thumbnail() ) {
        $img = get_the_post_thumbnail( $recent["ID"] );
    } else {
        $img = '<img src="path/to/image" />';
                }
    $args = array( 'numberposts' => '3');
    $recent_posts = wp_get_recent_posts( $args );
    foreach ( $recent_posts as $recent ) {
        echo '<div class="l-four"><div class="l-twelve l-mb1 recentThumb t-center">' . $img .'</div><div class="l-twelve f-size14 f-l-height16 t-center"><a href="' . get_permalink($recent["ID"]) . '" class="c-gold">' . $recent["post_title"] .'</a></div></div>';               
    }
?>

从您的代码来看,您似乎在实际拥有相关帖子之前尝试获取缩略图。例如,当 $recent 对象似乎仍然不存在时,您正在引用 $recent["ID"]。我猜这样的东西对你有用:

$args = array( 'numberposts' => '3');
$recent_posts = wp_get_recent_posts( $args );
foreach ( $recent_posts as $recent ) {
    if ( has_post_thumbnail($recent["ID"]) ) {
        $img = get_the_post_thumbnail( $recent["ID"] );
    } else {
        $img = '<img src="path/to/image" />';
    }

    echo '<div class="l-four"><div class="l-twelve l-mb1 recentThumb t-center">' . $img .'</div><div class="l-twelve f-size14 f-l-height16 t-center"><a href="' . get_permalink($recent["ID"]) . '" class="c-gold">' . $recent["post_title"] .'</a></div></div>';               
}