vendredi 27 octobre 2017

Do something If post has a term from a custom taxonomy

I've got a custom taxonomy "library" that has 2 terms in it: "fiction" and "novels"

I am trying to do a function depending on what term from this taxonomy my post has.

So if the post is assigned to "fiction", I need to //do something, and if the post is assigned to "novels" that I need to //do something else

At very first, I've been trying with is_tax, but that doesn't seem to work as expected:

if ( is_tax('library','fiction' ) ) {   
    //do something
  } elseif ( is_tax('library','novels' ) ) {    
    //do something else
  }

I have also tried has_term but that doesn't work for me either.

if ( has_term ('fiction','library' ) ) {    
        //do something
      } elseif ( has_term ('novels','libary' ) ) {  
        //do something else
      }

So I want to give it a go with wp_get_post_terms, but I'm not sure exactly how to execute this one.

I'm trying this:

$terms = wp_get_post_terms( $post->ID, 'library' );
foreach ( $terms as $term ) {
        if($term->name == 'fiction') {
            // do something
        }
        elseif($term->name == 'novels') {
            // do something else
        }
}

Am I missing something there? Specially this last one?

Aucun commentaire:

Enregistrer un commentaire