I need to modify the following code to show a placeholder if there is no featured image available.

I understand that I need to add a if statement in the following code but wasn’t sure of the exact coding I needed. Obviously in plain english it’s going to be along the lines of if there is a thumbnail show it, if not show the placeholder.

<?php $rel = $related->show(get_the_ID(), true);
     $count = 1;
    foreach ($rel as $r) {
     $class= ($count%6 == 0)?"category-related-item-right":"";

     echo '<div class="category-related-item '.$class.'"><a href="https://wordpress.stackexchange.com/questions/44208/.get_permalink($r->ID).">'.'<div class=category-related-title>'.$r->post_title.'</div>'.get_the_post_thumbnail($r->ID, array(50,50)).'</a></div>';
$count++;
}?>

I’ve tried the following but something isn’t quite right as it’s breaking the page…

<?php $rel = $related->show(get_the_ID(), true);
$count = 1;
foreach ($rel as $r) {
$class= ($count%6 == 0)?"category-related-item-right":"";

echo '<div class="category-related-item '.$class.'"><a href="https://wordpress.stackexchange.com/questions/44208/.get_permalink($r->ID).">'.'<div class=category-related-title>'.$r->post_title.'</div>';
if (get_the_post_thumnail($r->ID)) : 
get_the_post_thumbnail($r->ID, array(50,50));
else :
echo '<img src="https://wordpress.stackexchange.com/questions/44208/image_url"/>';
endif;
echo '</a></div>';
$count++;
}?>

4 Answers
4

Misspelling of thumbnail (thumnail) in the if statement.

Also get_the_post_thumbnail does echo the thumbnail, but just returns the html. You need to echo it.

Also, for checking if a post has a thumbnail, you can use has_post_thumbnail.

 if ( has_post_thumbnail($r->ID)) {
    echo get_the_post_thumbnail($r->ID, array(50,50));
 }else{
    echo '<img src="https://wordpress.stackexchange.com/questions/44208/image_url"/>';
 }

Leave a Reply

Your email address will not be published. Required fields are marked *