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>';
}
This is how it looks now.
This is how I want it.
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>';
}
This is how it looks now.
This is how I want it.
Share Improve this question edited Feb 11, 2019 at 17:47 Krzysiek Dróżdż 25.6k9 gold badges53 silver badges74 bronze badges asked Feb 11, 2019 at 15:57 ugurcanugurcan 133 bronze badges1 Answer
Reset to default 1It'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";
}