MarkP
MarkP

Reputation: 2566

WordPress: if has post thumbnail, add class

I'm having problems adding a class to the post excerpt < p > tag if the post has a featured image.

This is the bit in the loop that adds the image if there is one:

<p class="post-excerpt">
    <?php 
      if ( has_post_thumbnail() ) {
         the_post_thumbnail('full', array('class'=>'featured-image hide-mobile'));          
      } 
    ?>

    <?php  modified_excerpt(); ?> 
</p>

This works fine. So, from this I thought that I would be able to do this:

<p class="post-excerpt <?php if ( has_post_thumbnail() ) { echo "post-with-thumb"; } ?>">

But, alas no. It doesn't even output anything. Can anyone shed some light on this?

Thanks

Upvotes: 1

Views: 5486

Answers (1)

Dave
Dave

Reputation: 3658

Try this:

<?php
$thumb = get_the_post_thumbnail();
?>
<p class="post-excerpt<?php echo $thumb != '' ? ' post-with-thumb' : '' ?>">
    <?php 
      if ( $thumb != '' ) {
         the_post_thumbnail('full', array('class'=>'featured-image hide-mobile'));          
      } 
    ?>
    <?php  modified_excerpt(); ?> 
</p>

According to http://codex.wordpress.org/Function_Reference/has_post_thumbnail there might be issues with the_post_thumbnail() (see the examples section).

Upvotes: 2

Related Questions