user1888427
user1888427

Reputation: 45

Wordpress get terms of specific category of each post and display it

What I want to do is get the terms of a specific category of each post and then display it in this post.

Should be simple that the code that I have written:

function wodarchive_entry($post_id = null) {

  $post = get_post( $post_id );
  $termsArray = get_the_terms( $post->ID, "category" );
  //Get the terms for this particular item
  $termsString = ""; //initialize the string that will contain the terms

  foreach ( $termsArray as $term ) { // for each term 
    $termsString .= $term->name.' ';
    $category_id = $term->parent;//create a string that has all the slugs 
    if($category_id == '203'){
       echo $termsString;
    }
  }             
}

Btw, this is not working. Well, almost. It is giving me also values of other categories, probably because the if statement plays until finds the condition.

Upvotes: 0

Views: 1215

Answers (1)

Ruben Pauwels
Ruben Pauwels

Reputation: 380

If you only want to get the matching terms in $termsString you should place the assignment inside the if-loop.

function wodarchive_entry($post_id = null) {
  $termsArray = get_the_terms( $post_id, "category" );
  //Get the terms for this particular item
  $termsString = ""; //initialize the string that will contain the terms

  foreach ( $termsArray as $term ) { // for each term 
    $category_id = $term->parent;//create a string that has all the slugs 
    if($category_id == '203'){
       $termsString .= $term->name.' ';
    }
  }
  echo $termsString;                
}

Upvotes: 1

Related Questions