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
檢視更多 >