WordPress Development Asked by mikkelbreum on December 22, 2021
I’m having a hard time getting a set of selected terms in a custom taxonomy presented in a specific way.
I have a hierarchical taxonomy ‘places’ and a post with the tagged terms:
England (x)
- London (x)
- Venue1 (x)
France (x)
- Paris (x)
- Venue2
Germany
- Berlin (x)
- Venue3 (x)
I need to print out:
myPostTitle : Venue1 (London - England)
Paris (France)
Venue3 (Berlin)
My problem is, that I can’t find a function that will return the tagged terms, in a manner that reflects the hierarchical relationships. I need to be able to determine:
I’m outside the loop, and would prefer not to run setup_postdata(). I have the post ID.
I doubt you're going to find a function that created the exact output you're using, so you're probably looking at two nested called to get_terms()
. I usually avoid most other taxonomy-related plugins in favor of get terms. Most of the other functions are wrappers for this one.
Here's some psuedo-code for what I'd do:
<?php
// Get all the top-level terms i.e. those without a parent
$top_level_terms = get_terms( 'my_taxonomy', array( 'parent' => 0 ) );
foreach( $top_level_terms as $top_term ) {
// get child terms. use parent for direct descendants or child_of for all descendents
$child_terms = get_terms( 'my_taxonomy', array( 'child_of' => $top_term->term_id ));
// list the parent term
printf(
'<a href="%1$s">%2%s</a> (',
esc_url( get_term_link( $top_term->term_id ) ),
esc_attr( $top_term->name )
);
// list all the child terms
foreach ( $child_terms as $child_term ) {
printf(
'<a href="%1$s">%2%s</a>, ',
esc_url( get_term_link( $child_term->term_id ) ),
esc_attr( $child_term->name )
);
}
echo ')';
}
That code's untested and surely needs some additional arguments from you, but hopefully that can get you started.
Answered by mrwweb on December 22, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP