Can anyone help?

I'm trying to show a default placeholder image on my posts when the user hasn't uploaded an image.

I have the below code BUT i need to rewrite it so that the link isn't applied to the placeholder image - only the uploaded image.

Unfortunately my PHP isn't great at all so would appreciate some help..

<div class="imageContainer"><a href="<?php the_permalink(); ?>">
    // Must be inside a loop.

    if ( has_post_thumbnail() ) {
    else {
        echo '<img src="' . get_bloginfo( 'stylesheet_directory' ) . '/images/shared/placeholder.jpg" />';
<div class="imageContainer">
    <?php if ( has_post_thumbnail() ) : ?>
        <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('size-2'); ?></a>
    <?php else : ?>
        <img src="<?php echo get_bloginfo( 'stylesheet_directory' ); ?>/images/shared/placeholder.jpg" />
    <?php endif; ?>
  • Thank you! I was getting in a pickle with how to write my link inside the function – V Neal Aug 30 '12 at 9:42

You can filter the thumbnail HTML before it is printed out. If it is empty – return the placeholder.

This should go into your theme’s functions.php:

add_filter( 'post_thumbnail_html', 'wpse_63591_default_thumb' );

function wpse_63591_default_thumb( $html )
    if ( '' !== $html )
        return '<a href="' . get_permalink() . '">' . $html . '</a>';

    return '<img src="' . get_bloginfo( 'stylesheet_directory' ) . '/images/shared/placeholder.jpg" />';    

In your template just use


No conditionals or complicated PHP needed anymore. :)

  • Thanks for the answer - forgive me if I'm being a little slow here, I'm quite new to wordpress. Where would I add the conditional 'link' part? – V Neal Aug 30 '12 at 10:17
  • @VNeal I made an update to my answer to make that more clear. – fuxia Aug 30 '12 at 10:37

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.