在Wordpress中列出所有帖子和相应的分类标准
问题描述:
我必须列出来自Wordpress自定义帖子类型的所有帖子,并只显示通过自定义分类标准创建的标题及其各自的类别。我的代码在这里,我在分类法上遇到了一些问题。在Wordpress中列出所有帖子和相应的分类标准
<?php
$args = array(
'post_type' => 'books',
'posts_per_page' => -1);
$myposts = get_posts($args);
$terms = get_the_terms($post->ID , 'category');
foreach ($myposts as $post) : setup_postdata($post); ?>
<h1><?php echo the_title(); ?></h1>
<p>Category: <?php echo $term->name; ?></p>
<?php endforeach;
wp_reset_postdata();?>
答
这是你更新的代码,试试这个:
<?php
$args = array(
'post_type' => 'books',
'posts_per_page' => -1);
$myposts = get_posts($args);
$terms = get_the_terms($post->ID , 'category');
foreach ($myposts as $post) : setup_postdata($post); ?>
<h1><?php echo the_title(); ?></h1>
<?php $categories = get_the_category($post->ID); ?>
<?php if(! empty($categories)): ?>
<?php foreach($categories as $category): ?>
<p>Category: <?php echo $category->name; ?></p>
<?php break; ?>
<?php endforeach; ?>
<?php endif; ?>
<?php endforeach;
wp_reset_postdata();?>
答
<?php $args = array(
'post_type' => 'books',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'slug'
),
),
);
$myposts = new WP_Query($args);
foreach ($myposts as $post) : setup_postdata($post) ?>
<h1><?php echo the_title(); ?></h1>
<?php $categories = get_the_category(get_the_ID()); ?>
<?php if(! empty($categories)): ?>
<?php foreach($categories as $category): ?>
<p>Category: <?php echo $category->name; ?></p>
<?php break; ?>
<?php endforeach; ?>
<?php endif; ?>
<?php endforeach;
wp_reset_postdata();?>
注: - 现在你会得到具有类taxnomoy所有职务。如果您发现任何问题,现在您会得到正确的结果。请告诉我。
答
我明白了!谢谢大家!
<?php
$terms = get_terms($post_taxonomy);
$args = array(
'post_type' => 'book',
'posts_per_page' => -1,
'post_taxonomy' => 'category',
);
$the_query = new WP_Query($args);
?>
<?php if ($the_query->have_posts()) : ?>
<?php while ($the_query->have_posts()) : $the_query->the_post();
$category = get_the_terms($post->ID, "category");
$category_name = "";
foreach ($category as $term) {
$category_name .= $term->name.' ';
}
?>
<h1><?php the_title(); ?></h1>
<p>Category: <?php echo $category_name; ?></p>
<?php endwhile; ?>
<?php endif; ?>
谢谢@ nerijus-masikonis,但它没有渲染类别。 =( –