vendredi 9 septembre 2016

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. Any help is appreciated.

Aucun commentaire:

Enregistrer un commentaire