Problem: I have a hierarchical taxonomy with multiple levels. I would like to create a View of this taxonomy and display terms only from one specific level of hierarchy, regardless of parent term.
Solution: Use a custom shortcode that produces a comma-separated list of city term IDs like 1,2,3,4. Then use this shortcode in a View of terms filtered by term ID as a shortcode attribute "terms". Here's a custom shortcode snippet:
// COMMA-SEPARATED LIST OF N-LEVEL TAXONOMY TERM IDS OR SLUGS // n => Number, hierarchical level // format => String "id" (default) or "slug" // taxonomy => String "taxonomy-slug" // Ex. [n-level-term n="2" format="slug" taxonomy="book-tax"] function n_level_terms_func($atts) { $a = shortcode_atts( array( 'n' => '0', 'format'=>'id', 'taxonomy' => '' ), $atts ); $tax = $a['taxonomy']; $terms = get_terms( $tax, array( 'hide_empty' => false) ); $returns = array(); foreach( $terms as $term ) { if( isset($term->term_id) ){ $ancestors = get_ancestors( $term->term_id, $tax ); $count = count( $ancestors ) + 1; if( $count == $a['n'] ) { $returns[] = $a['format'] == 'id' ? $term->term_id : $term->slug; } } } return implode( ',', $returns); } add_shortcode("n-level-terms", "n_level_terms_func");
Here's how you would add it to the View's shortcode attribute:
[wpv-view name="Filtered Term View" terms="[n-level-terms n='4' format='id' taxonomy='places']"]
Relevant Documentation:
https://developer.wordpress.org/reference/functions/get_terms/
https://developer.wordpress.org/reference/functions/get_ancestors/
This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.
Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | - | - |
13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | - | - |
Supporter timezone: America/New_York (GMT-04:00)
This topic contains 2 replies, has 2 voices.
Last updated by 5 years, 9 months ago.
Assisted by: Christian Cox.