最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

categories - How to exclude a category returned by get_categories from function.php?

programmeradmin10浏览0评论

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 badges
Add a comment  | 

1 Answer 1

Reset to default 0

You'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.

发布评论

评论列表(0)

  1. 暂无评论