In my sidebar.php I have some code that prints the recent comments.

I could not share the complete code here because of the formating restrictions. You can find the code here: https://codeshare.io/p8xjp

  1. How can I display a custom fallback image (img from a directory) if the post does not have a featured image?

  2. How can I lik the fallback images and featured images to the permalink?

1 Answer 1


Here's the relevant part of your code that should work:

// This will make a URL like http://yoursite.com/path/to/fallback.png
$fallback_image = site_url( '/path/to/fallback.png' ); 
$fallback_image = "<img src='{$fallback_image}' />";

foreach( $recent_posts as $recent ){        
    echo '<div class="sidebar-entries">';
    $featured_image = get_the_post_thumbnail( $recent['ID'], 'sidebar-thumb', array( 'class' => 'sidebar-image' ) );

    if ( ! strlen( $featured_image ) ) {
        $featured_image = $fallback_image;

    $permalink = '<a href="' . get_permalink( $recent['ID'] ) . '">%s</a>';

    echo sprintf( $permalink, $featured_image );

    echo '<div class="sidebar-entries-title">';
    echo sprintf( $permalink, __( $recent["post_title"] ) );
    echo '<div class="sidebar-date">';

    $timestamp = '<p>' . human_time_diff( strtotime( $recent['post_date'] ), current_time('timestamp') ) . ' ago </p>';
    echo sprintf( $permalink, $timestamp );
    echo '</div>';
    echo '</div>';
    echo '</div>';

The basic idea is

  • Store your fallback image in a variable outside of your loop
  • Get the featured image in the loop and store it in a variable
  • If you get an empty string ( ! strlen() )
    • Replace the contents of your featured image variable with the fallback image variable

EDIT: Sorry, forgot about the permalink part. This approach uses sprintf to make your permalink code consistent.

  • Works like a charm! But what do you mean by storing outside the loop? Does that mean outside the wp-content folder?
    – Arete
    Apr 25, 2016 at 12:16
  • @Arete "Outside the loop" refers to being defined outside of the foreach controls structure, or "loop". By storing $fallback_image outside of the foreach, the value only has to be defined once instead of each time the foreach iterates.
    – phatskat
    May 1, 2022 at 2:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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