0

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?

0

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 '16 at 12:16

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.