Wordpress 类别:如何在单个 post 中显示名称、别名、描述和 link?

Wordpress categories: how to display name, slug, description and link inside single post?

我想做的是,在single.php内,分别拉取Category的不同属性,像这样:

<?php if ( have_posts() ) : ?>
    <?php while ( have_posts() ) : the_post(); ?>

        <a class="CATEGORYSLUG" href="CATEGORYLINK">
            <i class="fas CATEGORYDESCRIPTION"></i>
            <span>CATEGORYNAME</span>
        </a>

    <?php endwhile; ?>
<?php endif; ?>

要生产这样的最终产品:

这样我就可以使用:

  1. 类别 slug 作为 CSS class,为每个类别设计独特的颜色
  2. 类别描述作为字体真棒class(在本例中,"fa-wrench"),为每个类别分配一个唯一的图标

(对于这个项目,每个 post 只会分配一个类别,但我想一个面向未来的解决方案需要以这种格式输出分配给 post 的所有类别。 )

所以我真的只需要知道如何单独拉动:

  1. 类别别名
  2. 类别link
  3. 类别描述
  4. 类别名称

您可以使用以下代码获取它。

$postcat = get_the_category( $post->ID );

它是 return 您想要了解更多信息的所有字段,请参阅此 https://developer.wordpress.org/reference/functions/get_the_category/

您可以使用 get_the_terms() 函数获取分配给该 post 对象的所有类别,并遍历每个类别以创建您的图标等。

下面是一个示例,我已经调用了每个单独的变量,以便您可以清楚地看到对象属性。

如果您只分配了一个类别,这也适用。

//get all categories:
$categories = get_the_terms(get_the_ID(), 'category');

//loop through categories
foreach ($categories as $category) {
    //get variables
    $slug   = $category->slug;
    $link   = get_term_link($category->term_id);
    $descr  = $category->description;
    $name   = $category->name;

    //echo your content
    echo '<a class="'.$slug.'" href="'.$link.'"><i class="fas '.$descr.'"></i><span>'.$name.'</span></a>';
}