在自定义帖子类型中获取单个帖子的类别
问题描述:
我正在尝试获取自定义帖子类型循环中单个帖子的类别的未格式化列表(最好是一个slug)。这个列表最终将作为一个div的类($CATEGORYSLUGSWILLEVENTUALLYGOHERE
)。在自定义帖子类型中获取单个帖子的类别
我发现了几种不同的方法来获取一个自定义帖子类型的所有类别的列表,但不是一个特定的单个类别的列表。这是我到目前为止有:
<?php $projects_loop = new WP_Query(array('post_type' => 'projects', 'orderby' => 'menu_order')); ?>
<?php while ($projects_loop->have_posts()) : $projects_loop->the_post(); ?>
<div class="box <?php $CATEGORYSLUGSWILLEVENTUALLYGOHERE; ?>">
<div class="port-item-home">
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('portfolio-home'); ?></a>
<p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
</div>
</div>
<?php endwhile; ?>
而且这里是我到目前为止已经试过让类别列表:
<?php
$args = array(
'orderby' => 'name',
'parent' => 0,
'taxonomy' => 'project-type'
);
$categories = get_categories($args);
echo '<p> '.print_r(array_values($categories)).'something</p>'
?>
我有它返回数组 - 但阵列表明这将显示所有类别,而不是与特定帖子有关的类别。
我也试过:
<?php
//list terms in a given taxonomy (useful as a widget for twentyten)
$taxonomy = 'project-type';
$tax_terms = get_terms($taxonomy);
?>
<?php
foreach ($tax_terms as $tax_term) {
echo $tax_term->name;
}
?>
而这也显示所有类别,而不是有关职位的人。
有什么建议?
答
Got it!发现这篇文章,帮助我了:
https://wordpress.org/support/topic/how-to-get-the-category-name-for-a-custom-post-type
<!-- The Query -->
<?php
$args = array(
'post_type' => 'my_post_type',
'posts_per_page' => -1,
'orderby' => 'menu_order');
$custom_query = new WP_Query($args);
?>
<!-- The Loop -->
<?php
while ($custom_query->have_posts()) :
$custom_query->the_post();
$terms_slugs_string = '';
$terms = get_the_terms($post->ID, 'my_post_type');
if ($terms && ! is_wp_error($terms)) {
$term_slugs_array = array();
foreach ($terms as $term) {
$term_slugs_array[] = $term->slug;
}
$terms_slugs_string = join(" ", $term_slugs_array);
}
?>
<div class="box<?php echo $terms_slugs_string ?>">
<div class="port-item-home">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('portfolio-home'); ?>
</a>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</div>
</div>
<?php endwhile; ?>