I’ve got a custom post type that has hierarchical taxonomies set up. For an example, my post type of “project” has categories of

 A
   A.1
 B
 C

I’m trying to get the taxonomies displayed as classes on <li> items for each post, but I just want the top level parents shown. For the post I’m looking at, it is categorized as A.1 and C, but I’d like to return A and C.

I’m using 'parent' => 0 in the args, however its giving me A.1 and C. I have also tried using 'hide_empty' => 0 but that doesn’t seem to help.

Here’s my code:

 function project_get_item_classes($post_id = null) {
     if ($post_id === null)
         return;
     $_terms = wp_get_post_terms($post_id, 'construction_type', array( 'parent' => 0, 'hide_empty' => 0 ));
     foreach ($_terms as $_term) {
         echo " " . $_term->slug;
     }
 }

3 Answers
3

wp_get_post_terms doesn’t accept 'parent' or 'hide_empty' parameters in it’s arguments array, only 'orderby','order' and 'fields' but you are on the right track, simply add a conditional check before you echo out the slug:

function project_get_item_classes($post_id = null) {
     if ($post_id === null)
         return;
     $_terms = wp_get_post_terms($post_id, 'construction_type');
     foreach ($_terms as $_term) {
        if ($_term->parent == 0) //check for parent terms only
            echo " " . $_term->slug;
     }
 }

Leave a Reply

Your email address will not be published. Required fields are marked *