显示柱';Wordpress循环中的s类别

显示柱';Wordpress循环中的s类别,wordpress,Wordpress,我希望在我的主帖子循环中显示帖子所属的类别。我已经查看了Stackoverflow,但是答案似乎不起作用或者没有显示任何内容。我正在尝试以下方法: <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php $id = get_the_ID(); $cats = wp_get_post_categories($id); ?>

我希望在我的主帖子循环中显示帖子所属的类别。我已经查看了Stackoverflow,但是答案似乎不起作用或者没有显示任何内容。我正在尝试以下方法:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <?php 
        $id = get_the_ID();
        $cats = wp_get_post_categories($id);
    ?>
                    <?php foreach ( $cats as $cat ): ?>
                        <a href="<?php echo get_category_link($cat->cat_ID); ?>">
                            <?php echo $cat->name; ?>
                        </a>
                    <?php endforeach; ?>

                    <h5 class="card-title"><?php the_title(); ?></h5>
                    <p class="card-text"><?php the_excerpt(); ?></p>

<?php endwhile; else: ?>

    <p>Sorry, this page does not exist</p>

<?php endif; ?>

抱歉,此页面不存在


我不知道这里出了什么问题。

问题是
wp\u get\u post\u categories
返回一个术语id数组。在您的
foreach
中,您正在使用
$cat->XXX
作为链接和名称。但是,
$cat
不是一个对象。你还需要一步

您需要使用
get_category
来获取实际的category对象

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
    <?php 
        $id = get_the_ID();
        $cats = wp_get_post_categories($id);
    ?>
                    <?php foreach ( $cats as $cat ): 
                        // This is the new line.
                        $cat_object = get_category( $cat );
                     ?>

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

                    <h5 class="card-title"><?php the_title(); ?></h5>
                    <p class="card-text"><?php the_excerpt(); ?></p>

<?php endwhile; else: ?>

    <p>Sorry, this page does not exist</p>

<?php endif; ?>

抱歉,此页面不存在