背景

WordPress中的get_the_category函数不太常见,并且一般情况下很少被使用。然而get_the_category函数的主要功能是获取与查询参数相关的文章分类数据。借助这个功能,可以创建一些与文章相关的附加元素,如内部链接,以提高搜索引擎优化(SEO)的效果。简而言之,get_the_category函数有助于我们访问文章的分类信息,这有助于定制文章的显示方式以及增强网站的SEO策略。

函数原型

get_the_category函数位于wp-includes/category-template.php文件中。

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);
}

可以看到get_the_category函数与get_the_terms函数相关,至于get_the_terms函数的用法,这里就不多讲了,因为这个太偏僻导致作者也很少用,需要的可以自行查看WordPress开发手册。

参数

get_the_category( int $id = false )
  • $post->ID (当前文章的编号)

注意:这个函数只能在WordPress主循环中使用!

使用示例

显示类别的图片

<? php foreach((get_the_category()) as $category) {
    echo '<img src="http://www.uexf.com/images/'.$category - > cat_ID.'.jpg" alt="'.$category - > cat_name.'" />';
} ?>

显示第一个类别的名称

<? php $category = get_the_category();
echo $category[0] - > cat_name; ?>

显示第一个类别的连接

<?php $category = get_the_category();
if ($category[0]) {
    echo '<a href="' . get_category_link($category[0]->term_id) . '">' . $category[0]->cat_name . '</a>';
} ?>

获取指定文章编号的类别信息

<?php  global $post;
$categories = get_the_category($post->ID);
var_dump($categories);
?>

返回对象的成员

  • cat_ID: 类别编号
  • cat_name: 类别名称
  • category_nicename: 别名
  • category_description: 类别描述
  • category_parent: 父类别编号
  • category_count: 类别使用的数量

这个函数有助于获取文章的分类信息,您可以根据需要在WordPress主题中使用它,以定制文章的显示方式和提高SEO效果。

声明
1.本网站名称: 优易先锋资源网
2.本站永久网址:https://res.uexf.com
3.本网站的文章部分内容可能来源于网络,仅供大家学习与参考,如有侵权,请联系站长support@uexf.com
4.本站一切资源不代表本站立场,并不代表本站赞同其观点和对其真实性负责
5.本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
6.本站资源大多存储在云盘,如发现链接失效,请联系我们我们会第一时间更新