get_the_category()
云策文档标注
概述
get_the_category() 函数用于检索文章的分类信息,返回一个 WP_Term 对象数组。它支持在循环外使用,通过传递文章 ID 作为参数。
关键要点
- 函数返回默认“category”分类法下的分类,对于自定义分类法应使用 get_the_terms()
- 参数 $post_id 可选,默认为 false,表示使用当前文章 ID
- 返回值是 WP_Term[] 数组,包含分配给文章的分类对象
- 内部调用 get_the_terms() 并应用 _make_cat_compat() 进行兼容性处理
- 提供 apply_filters('get_the_categories', $categories, $post_id) 钩子用于过滤返回的分类数组
代码示例
// 获取文章分类并显示第一个分类名称
$categories = get_the_category();
if ( ! empty( $categories ) ) {
echo esc_html( $categories[0]->name );
}注意事项
- 仅适用于默认分类法,自定义分类法需使用 get_the_terms()
- 在循环外使用时需指定 $post_id 参数
原文内容
Retrieves post categories.
Description
This tag may be used outside The Loop by passing a post ID as the parameter.
Note: This function only returns results from the default “category” taxonomy.
For custom taxonomies use get_the_terms() .
Parameters
$post_idint|falseoptional-
The post ID. Defaults to current post ID.
Default:
false
Source
function get_the_category( $post_id = false ) {
$categories = get_the_terms( $post_id, 'category' );
if ( ! $categories || is_wp_error( $categories ) ) {
$categories = array();
}
$categories = array_values( $categories );
foreach ( array_keys( $categories ) as $key ) {
_make_cat_compat( $categories[ $key ] );
}
/**
* Filters the array of categories to return for a post.
*
* @since 3.1.0
* @since 4.4.0 Added the `$post_id` parameter.
*
* @param WP_Term[] $categories An array of categories to return for the post.
* @param int|false $post_id The post ID.
*/
return apply_filters( 'get_the_categories', $categories, $post_id );
}
Hooks
- apply_filters( ‘get_the_categories’, WP_Term[] $categories, int|false $post_id )
-
Filters the array of categories to return for a post.
Changelog
| Version | Description |
|---|---|
| 0.71 | Introduced. |
Skip to note 10 content
Codex
Show the First Category Name Only
$categories = get_the_category(); if ( ! empty( $categories ) ) { echo esc_html( $categories[0]->name ); }(Echoes the first array element ([0]) of
$categories.)Make the first category link to the category page:
$categories = get_the_category(); if ( ! empty( $categories ) ) { echo '<a href="' . esc_url( get_category_link( $categories[0]->term_id ) ) . '">' . esc_html( $categories[0]->name ) . '</a>'; }Skip to note 11 content
Stefano
Get the post category if you have a custom post_type
ID, 'taxonomy' ); // now you can view your category in array: // using var_dump( $categories ); // or you can take all with foreach: foreach( $categories as $category ) { echo $category->term_id . ', ' . $category->slug . ', ' . $category->name . '<br />'; }Skip to note 12 content
juanvillegas
Example response from function:
array(1) { [0]=> object(stdClass)#310 (17) { ["term_id"]=> ∫(6) ["name"]=> &string;(10) "familylife" ["slug"]=> &string;(10) "familylife" ["term_group"]=> int(0) ["term_taxonomy_id"]=> int(6) ["taxonomy"]=> string(8) "category" ["description"]=> &string;(0) "" ["parent"]=> ∫(0) ["count"]=> ∫(208) ["object_id"]=> int(7729) ["filter"]=> string(3) "raw" ["cat_ID"]=> ∫(6) ["category_count"]=> ∫(208) ["category_description"]=> &string;(0) "" ["cat_name"]=> &string;(10) "familylife" ["category_nicename"]=> &string;(10) "familylife" ["category_parent"]=> ∫(0) } }Skip to note 13 content
Codex
Show All Categories as Links
This outputs all the categories assigned to the post as links. Must be used inside the loop. You can also use the function
get_the_category_list()for this.$categories = get_the_category(); $separator = ' '; $output = ''; if ( ! empty( $categories ) ) { foreach( $categories as $category ) { $output .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" alt="' . esc_attr( sprintf( __( 'View all posts in %s', 'textdomain' ), $category->name ) ) . '">' . esc_html( $category->name ) . '</a>' . $separator; } echo trim( $output, $separator ); }Skip to note 14 content
Codex
Get the Post Categories From Outside the Loop
Skip to note 15 content
fgilio
To display a list of categories associated with a post, separated by commas, write this code:
<br />
$cats = array();<br />
foreach (get_the_category($post_id) as $c) {<br />
$cat = get_category($c);<br />
array_push($cats, $cat->name);<br />
}</p>
<p>if (sizeOf($cats) > 0) {<br />
$post_categories = implode(', ', $cats);<br />
} else {<br />
$post_categories = 'Not Assigned';<br />
}</p>
<p>echo $post_categories;<br />
Skip to note 16 content
kommasri
Display all categories with name and description
<div> name."<br>"; echo category_description($category); } ?> </div>Skip to note 17 content
soullighter
Show list of categories with comma
</pre> </div><!-- .comment-content --> <section id='feedback-4794' class='wporg-has-embedded-code feedback hide-if-js' data-comment-count='0'> </section><!-- .feedback --> <footer class='feedback-links wporg-dot-link-list' > <a role="button" class="feedback-login" href="https://login.wordpress.org/?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fget_the_category%2F%3Freplytocom%3D4794%23feedback-editor-4794" rel="nofollow">Log in to add feedback</a></footer> </article><!-- .comment-body --> </li> <li id="comment-305" data-comment-id="305" class="comment byuser comment-author-codex odd alt thread-odd thread-alt depth-1"> <article id="div-comment-305" class="comment-body"> <a href="#comment-content-305" class="screen-reader-text">Skip to note 18 content</a> <header class="comment-meta"> <div class="comment-author vcard"> <span class="comment-author-attribution"> <a href="https://profiles.wordpress.org/codex/" rel="external nofollow" class="url">Codex</a> </span> <a class="comment-date" href="https://developer.wordpress.org/reference/functions/get_the_category/#comment-305"> <time datetime="2015-06-28T16:34:02+00:00"> 11 years ago </time> </a> </div> <div class="user-note-voting" data-nonce="48cb425781" data-can-vote="false"><a class="user-note-voting-up" title="You must log in to vote on the helpfulness of this note" data-id="305" data-vote="up" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fget_the_category%2F%23comment-305"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a><span class="user-note-voting-count " title="100% like this"><span class="screen-reader-text">Vote results for this note: </span>1</span><a class="user-note-voting-down" title="You must log in to vote on the helpfulness of this note" data-id="305" data-vote="down" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fget_the_category%2F%23comment-305"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a></div> </header> <!-- .comment-metadata --> <div class="wporg-has-embedded-code comment-content" id="comment-content-305"> <p><strong>Show Category Images</strong><br /> This outputs category images named after the <code>cat_ID</code> with the alt attribute set to <code>cat_name</code>. You can also use any of the other member variables instead.</p> <pre class="wp-block-code"><code lang="php" class="language-php line-numbers">term_id ) . '.jpg' ) . '" alt="' . esc_attr( $category->name ) . '" />'; }