1

I use this to display the featured image for each post. If the post does not have a featured image, a generic image will be displayed:

<?php
if ( has_post_thumbnail() ) {
    echo '<a href="' . get_permalink($post->ID) . '" >';
    the_post_thumbnail();
    echo '</a>';
} else {
    echo '<img src="<?php bloginfo('template_directory'); ?>/img/fallback-featured-image.jpg" />';
}

How can I get the fallback image to link to the permalink?

3

I have updated your code so that the fallback image has post permalink. I hope this helps:

if ( has_post_thumbnail() ) {
   echo '<a href="' . get_permalink($post->ID) . '" >';
   the_post_thumbnail();
   echo '</a>';
} else {
        echo '<a href="' . get_permalink($post->ID) . '" ><img src="'. get_stylesheet_directory_uri() . '/img/fallback-featured-image.jpg" /></a>';
}
| improve this answer | |
1

The problem is when you are trying to get the template directory. You are getting it instead of printing

bloginfo() prints the output

get_bloginfo() retrieves the output

So, the nice piece of code should look like this:

<?php

if ( has_post_thumbnail() ) {
    echo '<a href="' . get_permalink($post->ID) . '" >';
    the_post_thumbnail();
    echo '</a>';
} else {
    echo '<img src="';
    echo get_bloginfo('template_directory');
    echo '/img/fallback-featured-image.jpg" />';
}
| improve this answer | |
  • Thanks. I wanted to give a thumbs up but I am not cool enough yet :p – Arete Apr 24 '16 at 15:08
  • I've cleaned it to be free of redundant code. There was a loop which was not used. – Max Yudin Apr 24 '16 at 15:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.