当前浏览:首页 / WordPress钩子 / get_the_categories

apply_filters( 'get_the_categories', WP_Term[] $categories, int|false $post_id )

过滤文章的类别数组

cat

category 分类more...

themore...


参数

$categories

(WP_Term[]) 要为文章返回的类别数组。

$post_id

(int|false) 文章 ID



源码

查看源码 官方文档


更新日志

版本描述
4.4.0添加了$post_id参数
3.1.0开始引入

使用示例

  • 示例1

    从特定文章的循环中删除某些类别。

    假设我们要删除ID为5的文章的类别,类别slug是cat-slug-acat-slug-b

    /**
     * Remove certain categories on post loop for a specific post
     * @param array $categories Array of categories
     * @return array $categories filtred categories
     */
    function wpdocs_remove_selected_categories( $categories ) {
    	if ( 5 == get_the_ID() ) { // Check if it is a specific post.
    		
    		$categories_to_remove = array(
    			'cat-slug-a',
    			'cat-slug-b'
    		); // Array of categories slug to be remove.
    
    		foreach ( $categories as $index => $single_cat ) {
    
    			if ( in_array( $single_cat->slug, $categories_to_remove ) ) {
    				unset( $categories[ $index ] ); // Remove the category.
    			}
    		}
    	}
    	
    	return $categories;
    }
    add_filter( 'get_the_categories', 'wpdocs_remove_selected_categories' );