【问题标题】:WordPress Individual Category Name within wp_querywp_query 中的 WordPress 单个类别名称
【发布时间】:2017-03-27 14:34:38
【问题描述】:

使用下面的 wp_query 从三个不同类别中提取最新帖子。作为其中的一部分,我想显示适合每篇文章的类别名称,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();
?>

【问题讨论】:

    标签: php wordpress foreach categories


    【解决方案1】:

    您可以使用get_the_category() 获取链接到的类别 那个帖子。

    替换这个

    <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 由它自己包含,所以你不需要回显它。

    希望这会有所帮助!

    【讨论】:

    • 完美!谢谢劳纳克。将此答案标记为正确,也请随时为该问题投票!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多