1

I have a custom taxonomy as 'services' and custom post type as 'portfolio'. What I would like to do is; I want to list all the selected services under their parent taxonomy in single page.

This is what I would like to achieve:

  • Design (parent - not selected): web, graphic, print (selected child taxonomies)
  • Development (parent - not selected): app, game, web (selected child taxonomies)

And here is my code:

$terms = get_the_terms( $post->ID, 'services' );

foreach ( $terms as $term ) {
  $parent = get_term_by('id', $term->parent, 'services');
  $parent_obj = get_term($parent->term_id, 'services');
  $parent_name = $parent_obj->name;

  echo $parent_name . ': ' . $term->name . '<br>';
}

enter image description here

This is how it looks now.

enter image description here

This is how I want it.

1

It's not so hard, but some PHP coding will be needed this time. Here's the code that will do the trick (assuming that there are only 2 levels in that hierarchy):

$post_terms = get_the_terms( $post->ID, 'services' );
$terms = array();

foreach ( $post_terms as $term ) {
    if ( $term->parent ) {
        if ( ! array_key_exists( $term->parent, $terms ) ) {
            $terms[ $term->parent ] = array(
                'term' => get_term( $term->parent, 'services' ),
                'children' => array()
            );
        }
        $terms[ $term->parent ]['children'][] = $term;
    } else {
        if ( ! array_key_exists( $term->term_id, $terms ) ) {
            $terms[ $term->term_id ] = array(
                'term' => $term,
                'children' => array()
            );
        }
    }
}

foreach ( $terms as $term_info ) {
    echo $term_info['term']->name;
    if ( ! empty($term_info['children']) ) {
        echo ': ';
        foreach ( $term_info['children'] as $i => $child ) {
            if ( $i ) echo ', ';
            echo $child->name;
        }
    }
    echo "<br/>\n";
}
  • Thank you so much. It worked like charm... – ugurcan Feb 11 at 20:49

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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