Search code examples
phpwordpressif-statementvar

WP fallback image in echo statement


I am echoing back some HTML for a related posts widget. I want to show the thumbnail image ('get_the_post_thumbnail') if it has one, if not show a fallback. I dont know if I should use the if/else statement in a var (can't get it to work) or what the best method for doing this is.

Here is my echo code:

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>';

I have tried using the if/else in a var:

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

and echo that out:

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>';

but it just defaulted to the else statement, not picking up the thumbnail from articles that have it.

Entire Code block

<?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>';               
    }
?>

Solution

  • From your code, it looks like you are trying to fetch the thumbnail before you actually have the related posts. For example, you are referencing $recent["ID"] when the $recent object still doesn't seem to exist. I guess something like this could work for you:

    $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>';               
    }