
The get_the_category function is rarely used in WordPress to obtain category information. Its function is to retrieve data related to query parameters. By utilizing this property, we can create article related items, add internal links, and improve SEO optimization results.
function prototype
The get_the_category function is located in the wp-includes/category template. php file.
function get_the_category( $id = false ) { $categories = get_the_terms( $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 `$id` parameter. * * @param array $categories An array of categories to return for the post. * @param int $id ID of the post. */ return apply_filters( ‘get_the_categories’, $categories, $id ); }
You can see that the get_the_category function is related to the get_the_terms function. As for the usage of the get_the_terms function, I won’t go into detail here. It’s too remote and I rarely use it. If you need it, you can check the WordPress development manual by yourself.
parameter
get_the_category( int $id = false )
$post->ID (当前文章的编号)
注意,这个函数只能在WordPress主循环中使用!
Simple usage
Display images of categories
<?php foreach((get_the_category()) as $category) { echo ‘<img src=” http://www.2zzt.com/images/ ‘ . $category->cat_ID . ‘.jpg” alt=”‘ . $category->cat_name . ‘” />’; } ?>
Display the name of the first category
<?php $category = get_the_category(); echo $category[0]->cat_name; ?>
Display the connection of the first category
<?php $category = get_the_category(); if($category[0]){ echo ‘<a href=”‘.get_category_link($category[0]->term_id ).'”>’.$category[0]->cat_name.'</a>’; } ? >
Retrieve category information for the specified article number
<?php global $post; $categories = get_the_category($post->ID); var_dump($categories); ?>
Return the members of the object
cat_ID
Category number, stored in the term_id field
cat_name
Category name, stored in the name field
category_nicename
Alias, stored in the slug field
category_description
Category description, stored in the description field
category_parent
Parent category number, 0 for those without a parent category, stored in the parent field
category_count
The number of categories used, stored in the count field

Comments (0)