get_the_categories
云策文档标注
概述
get_the_categories 是一个 WordPress 过滤器,用于修改返回给文章的类别数组。它允许开发者在获取文章类别时进行自定义过滤,例如移除特定类别。
关键要点
- 过滤器名称:get_the_categories
- 参数:$categories(WP_Term[] 数组,表示文章的类别数组)和 $post_id(int|false,表示文章 ID)
- 用途:过滤文章返回的类别数组,常用于在文章循环中移除或修改类别
- 版本历史:从 3.1.0 版本引入,4.4.0 版本添加了 $post_id 参数
代码示例
/**
* 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' );注意事项
使用此过滤器时,需确保正确处理 $post_id 参数以针对特定文章进行过滤,避免影响其他文章。示例代码展示了如何基于文章 ID 移除特定 slug 的类别。
原文内容
Filters the array of categories to return for a post.
Parameters
$categoriesWP_Term[]-
An array of categories to return for the post.
$post_idint|false-
The post ID.
Source
return apply_filters( 'get_the_categories', $categories, $post_id );
Skip to note 2 content
Sumit Singh
Remove certain categories from being display on post loop for a specific post.
Assume we want to remove categories with slug
cat-slug-aandcat-slug-bfor post with ID5/** * 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' );