Setting a default placeholder image WITHOUT link

Can anyone help?

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

Read More

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>

Related posts

Leave a Reply

2 comments

  1. <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>
    
  2. 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. 🙂