I have a View and I want to filter it to show only top-level terms. Christian helped me set up Custom Code to do this for another Custom Taxonomy - I would like to use the same logic to apply the filter to the current Custom Taxonomy I'm working with ("video-category").
Here is my View: hidden link
The Custom Code Christian set up for me (for a different Custom Taxonomy, "my-classes") is the following:
<?php
toolset_snippet_security_check() or die( 'Direct access is not allowed' );
// Add shortcode to filter for n-level term or ID
function n_level_term_func($atts) {
$a = shortcode_atts( array(
'n' => '0',
'format'=>'id',
), $atts );
$current_taxonomy = get_queried_object()->taxonomy;
$id = 0;
$slug = '';
if( $current_taxonomy == 'my-classes' ) {
$ancestors = get_ancestors( get_queried_object()->term_id, $current_taxonomy );
$count = count( $ancestors );
$id = isset( $ancestors[ $count - $a['n'] ] ) ? $ancestors[ $count - $a['n']] : get_queried_object()->term_id;
$term= get_term( $id, $current_taxonomy);
$slug = isset($term->slug) ? $term->slug: $slug;
}
return $a['format']=='slug' ? $slug : $id;
}
add_shortcode("n-level-term", "n_level_term_func");
I have used this custom shortcode successfully to filter for top-level terms in other Views, for example [wpv-view name="class-parts-filtered-by-term" terms="[n-level-term n="1"]"].
The Custom Taxonomy I want to use in the View in this case is "video-category."
Here is how I am displaying the View on the page: [wpv-view name="video-categories-1" terms="[n-level-term n="1"]"]
(Here is the Test Page: hidden link)
Can you help me modify this Custom Code or make a new one so I can filter my Video Categories by top-level term? Thank you!
Hello,
I assume you are going to display all top level term of taxonomy "video-category", it does not need custom codes, you can create a taxonomy view:
- Query terms of taxonomy "video-category"
- Filter by:
Select taxonomy terms whose parent is None.
See screenshot top-term.JPG
It worked!! Thank you, Luo, I had no idea about this easy solution. You're the best!