在wordpress中过滤类别

I want to add a filter to get_categories function.

I tried this:

function wpr_cat_filter($args) {
  $args['include'] = '37';
  return $args;
} 
add_filter('get_categories','wpr_cat_filter');

but it doesn't seem to be working. Any ides of what is wrong?

The filter doesn't actually seems to be applied.

If you check the "get_categories" function (in wp-includes/category.php), there's no "get_categories" filter applied:

function &get_categories( $args = '' ) {
        $defaults = array( 'taxonomy' => 'category' );
        $args = wp_parse_args( $args, $defaults );

        $taxonomy = apply_filters( 'get_categories_taxonomy', $args['taxonomy'], $args );

        // Back compat
        if ( isset($args['type']) && 'link' == $args['type'] ) {
                _deprecated_argument( __FUNCTION__, '3.0', '' );
                $taxonomy = $args['taxonomy'] = 'link_category';
        }

        $categories = (array) get_terms( $taxonomy, $args );

        foreach ( array_keys( $categories ) as $k )
                _make_cat_compat( $categories[$k] );

        return $categories;
}

Also, if you check the source:

wordpress$ grep -Ri "apply_filters" * | grep get_categories
wp-includes/default-widgets.php:            wp_dropdown_categories(apply_filters('widget_categories_dropdown_args', $cat_args));
wp-includes/default-widgets.php:        wp_list_categories(apply_filters('widget_categories_args', $cat_args));
wp-includes/category.php:   $taxonomy = apply_filters( 'get_categories_taxonomy', $args['taxonomy'], $args );

Perhaps it is just a placeholder for a filter that you can add yourself or might be added later.

If you want that filter, change the get_category function:

function &get_categories( $args = '' ) {
        $defaults = array( 'taxonomy' => 'category' );
        $args = wp_parse_args( $args, $defaults );
        $args = apply_filters( 'get_categories', $args );

        $taxonomy = apply_filters( 'get_categories_taxonomy', $args['taxonomy'], $args );

        // Back compat
        if ( isset($args['type']) && 'link' == $args['type'] ) {
                _deprecated_argument( __FUNCTION__, '3.0', '' );
                $taxonomy = $args['taxonomy'] = 'link_category';
        }

        $categories = (array) get_terms( $taxonomy, $args );

        foreach ( array_keys( $categories ) as $k )
                _make_cat_compat( $categories[$k] );

        return $categories;
}

You might want to file a bug with wordpress or ask on their mailing list to find out why this filter isn't being applied!