0

My single.php shows the featured image:

if ( has_post_thumbnail( ) ){
the_post_thumbnail( 'full',array('class'=>'img-responsive') );
}

I don't want the featured image displayed if the post is in certain categories.

I have no idea how to write the code, none of the suggestions I found helped me.

  • Should be something like "if the post has thumbnail but IS NOT in categories with IDs X and Y, then show the thumbnail". – Alex Mar 13 '18 at 14:18
1

has_category() will do the trick. You can pass it an ID or slug, or an array of IDs or slugs, and it will return true if the post has any of the given categories:

// ID
if ( has_category( 1 ) ) {
    the_post_thumbnail( 'full', array( 'class' => 'img-responsive' ) );
}

// Slug
if ( has_category( 'one' ) ) {
    the_post_thumbnail( 'full', array( 'class' => 'img-responsive' ) );
}

// IDs
if ( has_category( [1, 2, 3] ) ) {
    the_post_thumbnail( 'full', array( 'class' => 'img-responsive' ) );
}

// Slugs
if ( has_category( ['one', 'two', 'three'] ) ) {
    the_post_thumbnail( 'full', array( 'class' => 'img-responsive' ) );
}

And you can check if the post is not in certain categories by adding ! to the condition, to indicate 'is not':

if ( ! has_category( [1, 2, 3] ) ) {
    the_post_thumbnail( 'full', array( 'class' => 'img-responsive' ) );
}
  • In understand, but you left out the other "if" - if ( has_post_thumbnail( ). The code should check for that too. – Alex Mar 13 '18 at 14:24
  • I'm just showing how to check if the post has a category or not, you can mix or match it with any other conditions you like. – Jacob Peattie Mar 13 '18 at 14:26
  • 1
    Thank you so much, it did the trick. Here is my final code: if ( has_post_thumbnail( ) && ! has_category( 240 )) – Alex Mar 13 '18 at 14:28
  • No problem. It'd be swell if you could accept the answer. – Jacob Peattie Mar 13 '18 at 14:31

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.