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:

$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) {
    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.


You'll find an appropriate filter in the get_terms function which is called by get_categories.

See source code https://github.com/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.org/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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.