I have custom post type products & custom taxonomy product_type which has many terms & the products can have multiple product_type terms assigned to it Ex. A Samsung TV Model post has product_type as New arrivals , featured & tv . I am trying to output only the specific custom taxonomy term [hyperlink] from an array on a single products post :-

if( has_term( array( 'laptop', 'TV', 'phone', 'tablet' ), 'product_type' ) ) :
  // Do stuff here
else :

entering a text instead of // Do stuff here in above code works. I want to echo the actual tax term from that array. Tried echo $term; , echo get_the_term(); but it doesnt work. How do i output the custom term from this array ?

  • Please share your full query, only sharing a tiny portion of it doesn't make sense. – obiPlabon Feb 27 '18 at 15:37

You're checking if a product_type has a term using has_term(). Now you need to actually get the terms using get_terms(). That function can technically return from 1 to 4 terms. If more than one of the terms is set, you'll need to pick one. In the following code, I chose the first since there's guaranteed to be at least one term.

if( has_term( [ 'laptop', 'TV', 'phone', 'tablet' ], 'product_type' ) ) {
  //* Get the terms
  $terms = get_terms( [
    'taxonomy' => 'product_type',
    'slug'     => [ 'laptop', 'TV', 'phone', 'tablet' ],
  ] );
  //* There could still be up to 4 terms, so use the first
  echo $terms[0]->name;
  • thanks Nathan its works ,so we had to define the $terms cud tell abt this line - //* There could still be up to 4 terms, so use the first what it means ? does it mean the code will not work if suppose we have 5 or 6 terms in that square bracket ? coz i find this weird prob that if i enter 5 terms , it keeps on displaying the wrong term – Charlesbz Mar 2 '18 at 19:44
  • Also is there a way we could hyperlink the term as my intial question was abt the term which wud be clickable i.e. using something like $term->slug ? – Charlesbz Mar 2 '18 at 19:50
  • Nathan can u correct the code ? i think the prob is that [0] Wrong term gets displayed – Charlesbz Mar 5 '18 at 3:30
  • $term[0] displays the 1st term from get_terms which actually checks for all the terms & not the terms that are attached to the current post. That has_term function only for conditional purpose seems of no help in current code because the get_term doesnt behave according to it... – Charlesbz Mar 6 '18 at 11:29

Your Answer

