在 wordpress 循环中显示帖子的类别? [英] Display a post's category within the wordpress loop?

查看:24
本文介绍了在 wordpress 循环中显示帖子的类别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我创建了一个 Wordpress 模板,该模板仅显示与锻炼"类别相关联的帖子.在显示这些的循环中,我希望列出特定帖子的类别.

我在想这样的事情会奏效:

$id = get_the_ID();$cats = wp_get_post_categories($id);

但后来我不知道如何在屏幕上显示出来.任何人都知道如何在循环中显示每个帖子的类别?我看过的所有文章都只展示了如何显示所有类别,而不是显示与特定帖子关联的类别.

这是我的循环:

<b><a href="<?php the_permalink() ?>><?php the_title();?></a></b><?php$id = get_the_ID();$cats = wp_get_post_categories($id);?>

<?php endwhile;?>

解决方案

获取类别对象:

$cats = get_the_category($id);


只需回显名称:

echo $cats[0]->name;


如果你想输出一个链接,使用这个:

<a href="<?php echo get_category_link($cats[0]->cat_ID);?>>><?php echo $cats[0]->name;?></a>

注意:代替 wp_get_post_categories($id),您可以使用 get_the_category().


更新:如果您想显示所有类别,只需遍历它们:

<?php foreach ( $cats as $cat ): ?><a href="<?php echo get_category_link($cat->cat_ID);?>>><?php echo $cat->name;?></a><?php endforeach;?>

Okay, so I have a Wordpress template that I created that only displays posts that have the "workout" category associated with it. Within the loop that displays those, I want the categories of the specific post to be listed.

I was thinking something like this would work:

$id = get_the_ID();
$cats = wp_get_post_categories($id);

But then I do not know how to echo this out on to the screen. Anyone have any idea how I can display the categories of each post within the loop? All of the articles I have looked at have only showed how to display all categories, not display the categories associated with a specific post.

Here is the loop I have:

<div class="query">
<b><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></b>
    <?php 
        $id = get_the_ID();
        $cats = wp_get_post_categories($id);
    ?>
</div>
<?php endwhile; ?>

解决方案

Get the category objects:

$cats = get_the_category($id);


Just echo the name:

echo $cats[0]->name;


If you want to output a link, use this:

<a href="<?php echo get_category_link($cats[0]->cat_ID); ?>">
    <?php echo $cats[0]->name; ?>
</a>

Note: instead of wp_get_post_categories($id), you could just use get_the_category().


Update: if you want to display all the categories, just loop through them:

<?php foreach ( $cats as $cat ): ?>

    <a href="<?php echo get_category_link($cat->cat_ID); ?>">
        <?php echo $cat->name; ?>
    </a>

<?php endforeach; ?>

这篇关于在 wordpress 循环中显示帖子的类别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆