我的代码在工作中不是最优的 - 它没有正确显示父类别帖子。他不是只显示父类别的帖子,而是抛出属于父类别的所有子类别的所有帖子。我对函数“in_category”有疑问 - 自定义帖子类型是否有任何替换?代码如下:
<?php
$categories = get_terms('MY_CUSTOM_TAXONOMY',array('parent' => 0 , 'hide_empty'=> '0' ));
foreach ( $categories as $category ) {
if ( $category->parent > 0 ) {
continue;
}
$i = 0;
echo '<h1 style="font-weight:bold">' . $category->name . '</h1>';
$posts = get_posts( array( 'MY_CUSTOM_TAXONOMY' => $category->name, 'post_type' => 'CUSTOM_POST_TYPE' ) );
echo '<ul>';
foreach ( $posts as $post ) {
$child_categories = get_term_children( $category->term_id, 'MY_CUSTOM_TAXONOMY' );
if ( $child_categories && in_category( $child_categories, $post->ID ) ) {
continue;
}
setup_postdata($post);
echo '<li>'; the_title(); echo '</li>';
}
echo '</ul>';
$categories2 = get_terms('MY_CUSTOM_TAXONOMY',array('parent' => $category->term_id , 'hide_empty'=> '0' ));
foreach ( $categories2 as $category ) {
$j = 0;
echo '<h2>' . $category->name . '</h2>';
$posts = get_posts( array( 'MY_CUSTOM_TAXONOMY' => $category->name, 'post_type' => 'CUSTOM_POST_TYPE' ) );
echo '<ul>';
foreach($posts as $post) :
setup_postdata($post);
echo '<li>'; the_title(); echo '</li>';
endforeach;
echo '</ul>';
}
}
?>