简体   繁体   English

在循环中显示自定义帖子类型(特别是该帖子)的WordPress类别

[英]Display WordPress categories for Custom Post Types (specifically for that post) in the loop

I'm using a Javascript filter which shows and hide a list (loop) of Custom Post Types based on their category. 我正在使用Javascript过滤器,它根据类别显示和隐藏自定义帖子类型的列表(循环)。

I'm trying to add the category slug as a class. 我正在尝试将类别slug添加为类。 But I only want to display the categories that are assigned to a specific loop item. 但我只想显示分配给特定循环项的类别。 Each item can have multiple categories. 每个项目可以有多个类别。

I've done it this way, but it dumps all the categories on each loop, not ones specifically for that loop item. 我已经这样做了,但是它会在每个循环中转储所有类别,而不是专门针对该循环项的那些类别。

<?php
    $pageID = get_the_ID();
    $loop = new WP_Query(array('post_type' => 'casestudies', 'posts_per_page' => -1));
    $taxonomy = 'custom_casestudies';
    $terms = get_terms($taxonomy);
    while ($loop->have_posts()) : $loop->the_post();
?>

<div class="block-wrap mix <?php foreach ($terms as $term) echo  ' ' . $term->slug; ?>">
    // loop content
</div>

<?php endwhile; wp_reset_postdata(); ?>

get_terms returns all of the terms in the given taxonomy. get_terms返回给定分类中的所有术语。 In this case you should be using wp_get_post_terms, which returns a list of terms for a given post. 在这种情况下,您应该使用wp_get_post_terms,它返回给定帖子的术语列表。 The documentation goes into more detail. 文档更详细。

In case this helps anyone else and thanks to Matt (who answered) this is working. 如果这有助于其他任何人,并感谢Matt(谁回答)这是有效的。

<?php
    global $post;
    $loop = new WP_Query(array('post_type' => 'casestudies', 'posts_per_page' => -1));
    while ($loop->have_posts()) : $loop->the_post();
    $terms = wp_get_post_terms($post->ID, 'custom_casestudies');
?>
<div class="block-wrap mix<?php foreach ($terms as $term) echo  ' ' . $term->slug ?>">
    // content
</div>

<?php endwhile; wp_reset_postdata(); ?>

The terms have been to be after the while loop. 术语一直是在while循环之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM