get_the_category

函数
get_the_category ( $post_id = false )
参数
  • (int) $post_id Optional. The post ID. Defaults to current post ID.
    Required:
    Default: false
返回值
  • (WP_Term[]) Array of WP_Term objects, one for each category assigned to the post.
定义位置
相关方法
get_the_category_rssget_the_category_listget_categorythe_categoryget_the_category_by_id
引入
0.71
弃用
-

get_the_category: 这个函数检索当前文章所属的类别对象的数组。它不需要任何参数,返回一个WP_Term对象的数组。

检索文章的类别。

这个标签可以在The Loop之外使用,通过传递一个文章ID作为参数。

注意: 这个函数只返回默认的””类别””分类法的结果。对于自定义分类法,请使用get_the_terms()。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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 );
}
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 ); }
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 );
}

常见问题

FAQs
查看更多 >