wp_query 内的 WordPress 个人类别名称

WordPress Individual Category Name within wp_query

使用下面的 wp_query 从三个不同的类别中提取最新的 post。作为其中的一部分,我想显示适合每篇文章的类别名称,the_category(); 确实实现了,但是它在名称周围放置了 <a><li> 标签。我只想获取类别的名称?

<?php
$categories = get_categories();
foreach ($categories as $category)
{

}
$args = array(
    'cat' => 'article,fitness,recipe',
    'posts_per_page' => '3',
);

$query = new WP_Query($args);

if ($query->have_posts())
{

    ?>
    <?php
    while ($query->have_posts())
    {
        $query->the_post();
        ?>
        <article id="post-<?php the_ID(); ?>" class="col">
            <h5><?php echo the_category(); ?></h5>
        </article>

    <?php } // end while  ?> 
<?php
} // end if
wp_reset_postdata();
?>

You can use get_the_category() to get the category linked to that post.

替换这个

<article id="post-<?php the_ID(); ?>" class="col">
    <h5><?php echo the_category(); ?></h5>
</article>

有了这个

<article id="post-<?php the_ID(); ?>" class="col">
    <?php
    $category_detail = get_the_category(get_the_ID());
    $cat_arr = [];
    foreach ($category_detail as $cd)
    {
        $cat_arr[] = $cd->cat_name;
    }
    ?>
    <h5><?= !empty($cat_arr) ? implode(', ', $cat_arr) : 'N/A'; ?></h5>
</article>

仅供参考:the_category() echo 包含它自己所以你不需要回应它。

希望对您有所帮助!