Skip to content

Instantly share code, notes, and snippets.

@remcotolsma
Created May 29, 2015 19:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save remcotolsma/ec97601594e305419fbd to your computer and use it in GitHub Desktop.
Save remcotolsma/ec97601594e305419fbd to your computer and use it in GitHub Desktop.
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