在while循环中回显类别名称

时间:2018-10-25 11:42:42

标签: php wordpress

我在while循环中显示我的自定义帖子类型“项目”。但是所有帖子都位于不同的类别中,因此我想显示每个项目的类别名称,但它不会输出类别名称。

这是循环:

if ( $query->have_posts() ) {
                    while ($query->have_posts()) {
                        $query->the_post(); ?>
                        <?php if( has_post_thumbnail() ) { ?>
                            <div>
                                <img src="<?php echo the_post_thumbnail_url('home-project-thumb'); ?>" style="width: 100%; height: auto; max-height: 625px;">
                                <div style="background-image:url('<?php echo get_template_directory_uri(); ?>/assets/images/projectslider-<?php echo $color; ?>.svg'); background-repeat: no-repeat; background-size: cover;" class="projectslider-item">
                                    <div class="projectslider-content"><?php $categories = get_the_category(); $cat_name = $categories[0]->cat_name; ?>
                                        <a href="<?php the_permalink(); ?>"><h2><?php the_title(); ?></h2></a>
                                        <p <?php if ( is_page(95) ) { ?> style="color: white!important;" <?php } ?>><?php the_excerpt(); ?></p><br>
                                        <a href="<?php the_permalink(); ?>" class="projectslider-button projectslider-button-purple">Lees meer</a>
                                    </div>
                                </div>
                            </div>
                <?php } ?> <?php } } wp_reset_postdata(); ?>

我在循环中添加了以下代码:

<?php $categories = get_the_category(); $cat_name = $categories[0]->cat_name; ?>

2 个答案:

答案 0 :(得分:2)

如果您使用的是自定义分类法,则需要get_the_terms()

$terms = get_the_terms(get_the_ID(), 'category');
$term_name = $terms[0]->name;

category是您的自定义分类法的子名称。

PS:如果您使用默认的WordPress category,则get_the_terms()也可以使用(类似于上面的示例)。

答案 1 :(得分:0)

您似乎只是在为变量分配名称,您需要将其“回显”为输出:

<?php

$categories = get_the_category();

$cat_name = $categories[0]->cat_name;

echo $cat_name;

?>
相关问题