我必须列出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();?>
答案 0 :(得分:1)
这是您更新的代码,请尝试以下操作:
<?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();?>
答案 1 :(得分:1)
<?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的帖子。如果您发现任何问题,现在您将以错误的方式进行,您将获得正确的结果。请告诉我。
答案 2 :(得分:0)
我明白了!谢谢大家!
<?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; ?>