wordpress分类名称调用的几种情况

在WordPress中,如果你想调用当前分类的名称,可以使用single_cat_title()函数。以下是一些常见的使用方法和场景:

  1. 在分类页面调用当前分类名称

如果你正在分类存档页面(category.php)中,可以直接使用single_cat_title()函数来获取当前分类的名称。例如:

复制代码
<?php single_cat_title(); ?>

这个函数会输出当前分类的名称。如果你想将分类名称存储到一个变量中,可以这样写:

复制代码
<?php $current_category_name = single_cat_title('', false); ?>

这里,single_cat_title(", false)的第二个参数false表示不直接输出,而是返回分类名称。

  1. 在其他页面调用当前分类名称

如果你需要在非分类页面(如首页、文章页面等)调用当前分类名称,可以使用get_queried_object()函数来获取当前查询对象,然后通过term_id或name属性获取分类名称。例如:

复制代码
<?php
if (is_category()) {
    $current_category = get_queried_object();
    echo $current_category->name; // 输出当前分类名称
}
?>
  1. 在文章页面调用文章所属分类名称

如果你在文章页面(single.php)中,需要获取文章所属的分类名称,可以使用get_the_category()函数。例如:

复制代码
<?php
$categories = get_the_category();
if (!empty($categories)) {
    echo $categories[0]->name; // 输出文章的第一个分类名称
}
?>
  1. 在循环中调用分类名称

如果你在循环中(如index.php或archive.php)需要获取每个文章的分类名称,可以这样写:

复制代码
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
    <?php
    $categories = get_the_category();
    if (!empty($categories)) {
        echo $categories[0]->name; // 输出文章的第一个分类名称
    }
    ?>
<?php endwhile; endif; ?>

如果在分类页面,直接使用single_cat_title()。

如果在其他页面,使用get_queried_object()。

如果在文章页面,使用get_the_category()。

根据你的具体需求选择合适的方法即可。

原文

http://www.yanzidan.com/jianzhan/7732.html

相关推荐
hui-梦苑1 天前
[PHP]轻量主题函数WordPress 集成 KaTeX 数学公式渲染
开发语言·php·wordpress·katex
VIP_CQCRE2 天前
用 Ace Data Cloud 把 WordPress 变成你的 AI 内容营销中枢
ai·seo·wordpress·内容营销·ace data cloud
豆豆8 天前
2026 主流 CMS 建站系统对比分析:企业、个人建站该如何选型?
wordpress·建站系统·cms建站·企业建站·建站选型·saas建站·2026建站指南
VIP_CQCRE10 天前
用 Ace Data Cloud 自动发布 WordPress 文章:把 AI 写作变成可积累的 SEO 内容资产
ai·api·seo·wordpress·acedatacloud
VIP_CQCRE17 天前
用 Ace Data Cloud 自动发布 WordPress 文章:把 SEO 内容站变成长期增长资产
ai·自动化·seo·wordpress·acedatacloud
2601_9657984721 天前
Renovate Theme Setup: Fast Contractor & Construction Site Architecture
theme·wordpress
2601_9657984722 天前
Salient Theme Setup Guide for Fast Creative WordPress Sites
数据库·web3·php·wordpress
2601_9657984725 天前
Boutique Business Consulting WordPress Architecture & SEO Setup
android·theme·wordpress
2601_965798471 个月前
Plastic Surgery Clinic Web Setup: Deploying Rejuvita WordPress
php·theme·wordpress
2601_965798471 个月前
Contractor Web Setup: Deploying Bathrooms & Kitchens Theme Fast
前端·web3·php·wordpress