Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress filter to display only root categories and sub categories.
<?php
function prefix_get_the_terms( $terms, $post_id, $taxonomy ) {
if ( 'category' == $taxonomy ) {
if ( is_category() ) {
$current = get_queried_object();
$sub_terms = get_terms( $taxonomy, array(
'child_of' => $current->term_id,
'fields' => 'ids',
) );
$terms = array_filter( $terms, function( $term ) use( $sub_terms ) {
return in_array( $term->term_id, $sub_terms );
} );
} else {
$terms = array_filter( $terms, function( $term ) {
return 0 === $term->parent;
} );
}
}
return $terms;
}
function prefix_template_redirect() {
add_filter( 'get_the_terms', 'prefix_get_the_terms', 10, 3 );
}
add_action( 'template_redirect', 'prefix_template_redirect' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.