0

Below is part from a WP_Query loop.

I have two parent categories ABC and 12, and each has a few child categories.

In the first td I would like to have the category slug from ABC children and in the second from 12 children.

The post may be in one of the two child categories, or both. One from ABC and one from 12, or one from ABC or one from 12.

$inCat = get_the_category(get_the_ID());

echo "<td>".(!empty($inCat[0]->slug) ? $inCat[0]->slug : "")."</td>";
echo "<td>".(!empty($inCat[1]->slug) ? $inCat[1]->slug : "")."</td>";

How can this be accomplished?

1 Answer 1

2

Have a look at get_the_terms()?

<?php 
    // Change 'category' if using a custom taxonomy and not referring to the default blog categories
    $terms = get_the_terms( $post->ID, 'category' ); 
?>

<tr>
  <td><?php

    foreach($terms as $term) {

      // show which categorie(s) under ABC
      if( $term->parent == '0' ) ) {
        echo $term->name;
      } 

    }
  ?></td> 

  <td><?php

    foreach($terms as $term) {

      // show which categorie(s) under 12
      if( $term->parent == '1' ) ) {
        echo $term->name;
      }

    }
?></td>
</tr>
2
  • Hi, thank you for your help. Weird ... I have a custom post type defined quiz and I did this: $terms = get_the_terms( get_the_ID(), 'quiz' ); and it's giving me an error WP_Error Object ( [errors:WP_Error:private] => Array ( [invalid_taxonomy] => Array ( [0] => Invalid taxonomy ) ) . There's more ... but I think you get the idea.
    – Ciprian
    Jan 6, 2015 at 21:17
  • That's my bad, sorry, it should be the taxonomy NOT the custom post type.. I updated my answer.
    – deflime
    Jan 6, 2015 at 21:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.