I have a plugin that create my website sitemap. It starts by getting all categories with get_categories
and then gets all pages for each.
However I have one category that must not be included then I did that in the plugin code:
$args['exclude']=2;
$cats = get_categories( $args );
The problem is that if the plugin replace the file my modiofication will be deleted, I tried with that:
function exclude_cat($taxonomy, $args) {
$args['exclude']=2;
return $args;
}
add_filter('get_categories_taxonomy', 'exclude_cat', 10, 2);
But then no category is returned at all, I think I'm not using it correctly but I don't find examples.
I have a plugin that create my website sitemap. It starts by getting all categories with get_categories
and then gets all pages for each.
However I have one category that must not be included then I did that in the plugin code:
$args['exclude']=2;
$cats = get_categories( $args );
The problem is that if the plugin replace the file my modiofication will be deleted, I tried with that:
function exclude_cat($taxonomy, $args) {
$args['exclude']=2;
return $args;
}
add_filter('get_categories_taxonomy', 'exclude_cat', 10, 2);
But then no category is returned at all, I think I'm not using it correctly but I don't find examples.
Share Improve this question asked Oct 6, 2020 at 6:38 EntretoizeEntretoize 1331 silver badge6 bronze badges1 Answer
Reset to default 0You'll find an appropriate filter in the get_terms
function which is called by get_categories
.
See source code https://github/WordPress/WordPress/blob/master/wp-includes/taxonomy.php#L1247
We don't use any of the callback arguments in this case. We can use array_filter
on the list of terms (WP_Term) objects. See https://developer.wordpress/reference/classes/wp_term/
This allows us to remove a term with a particular ID
add_filter( 'get_terms', function( $terms, $taxonomies, $args, $term_query ){
return array_filter($terms, function( $term ) {
return $term->term_id !== 2;
});
}, 10, 4 );
Note that get_categories
by default only returns categories which have posts assigned, you can change that by adding hide_empty => false
to the $args
array.