WordPress读取分类信息可以使用到以下标签:get_cat_name、get_category、get_category_link;
其中:
get_cat_name,只输出分类名称;
get_category_link,只输出分类链接;
get_category,则输出分类信息,其中包括分类描述、目录、分类名称等;
详细使用方法如下。
读取分类名称:
<?php echo get_cat_name($cat_id); ?>
该标签会输出如:
WordPress标签
读取分类链接:
<?php echo get_category_link($cat_id); ?>
该标签会输出如:
https://e.69525.com/f/
读取分类信息:
<?php echo get_category($cat_id); ?>
该标签会输出如:
WP_Term Object
(
[term_id] => 52
[name] => WordPress标签
[slug] => f
[term_group] => 0
[term_taxonomy_id] => 23
[taxonomy] => category
[description] =>
[parent] => 0
[count] => 0
[filter] => raw
[cat_ID] => 52
[category_count] => 0
[category_description] =>
[cat_name] => WordPress标签
[category_nicename] => f
[category_parent] => 0
)
get_category()位于 /wp-includes/category.php 91行[6.0版本]
/**
* Retrieves category data given a category ID or category object.
*
* If you pass the $category parameter an object, which is assumed to be the
* category row object retrieved the database. It will cache the category data.
*
* If you pass $category an integer of the category ID, then that category will
* be retrieved from the database, if it isn't already cached, and pass it back.
*
* If you look at get_term(), then both types will be passed through several
* filters and finally sanitized based on the $filter parameter value.
*
* @since 1.5.1
*
* @param int|object $category Category ID or category row object.
* @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
* correspond to a WP_Term object, an associative array, or a numeric array,
* respectively. Default OBJECT.
* @param string $filter Optional. How to sanitize category fields. Default 'raw'.
* @return object|array|WP_Error|null Category data in type defined by $output parameter.
* WP_Error if $category is empty, null if it does not exist.
*/
function get_category( $category, $output = OBJECT, $filter = 'raw' ) {
$category = get_term( $category, 'category', $output, $filter );
if ( is_wp_error( $category ) ) {
return $category;
}
_make_cat_compat( $category );
return $category;
}
get_cat_name()位于 /wp-includes/category.php 223行[6.0版本]
/**
* Retrieves the name of a category from its ID.
*
* @since 1.0.0
*
* @param int $cat_id Category ID.
* @return string Category name, or an empty string if the category doesn't exist.
*/
function get_cat_name( $cat_id ) {
$cat_id = (int) $cat_id;
$category = get_term( $cat_id, 'category' );
if ( ! $category || is_wp_error( $category ) ) {
return '';
}
return $category->name;
}
get_category_link()位于 /wp-includes/category-template.php 20行[6.0版本]
/**
* Retrieves category link URL.
*
* @since 1.0.0
*
* @see get_term_link()
*
* @param int|object $category Category ID or object.
* @return string Link on success, empty string if category does not exist.
*/
function get_category_link( $category ) {
if ( ! is_object( $category ) ) {
$category = (int) $category;
}
$category = get_term_link( $category );
if ( is_wp_error( $category ) ) {
return '';
}
return $category;
}