Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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(); ?>">
           <?php
    // Must be inside a loop.

    if ( has_post_thumbnail() ) {
        the_post_thumbnail('size-2');
    }
    else {
        echo '<img src="' . get_bloginfo( 'stylesheet_directory' ) . '/images/shared/placeholder.jpg" />';
    }
    ?>
            </a></div>
share|improve this question

2 Answers 2

up vote 1 down vote accepted
<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; ?>
</div>
share|improve this answer
    
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

the_post_thumbnail('size-2');

No conditionals or complicated PHP needed anymore. :)

share|improve this answer
    
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. –  toscho Aug 30 '12 at 10:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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