可能不是最好的解决方案,但我设法得到了我需要的东西,而且效果很好。我也可以添加到输出html ul和li标签,以便按照我在开始时的要求创建列表,但这对我来说是可以的,并且这种设计不需要更多的样式。
$queried_taxonomy_name = $wp_query->queried_object->taxonomy;
$queried_term_id = $wp_query->queried_object_id;
$queried_term = get_term_by(\' id\', $queried_term_id, $queried_taxonomy_name );
function show_term_posts( $queried_posts, $term, $taxonomy ){
$term_children = get_term_children( $term->term_id, $taxonomy );
global $queried_term_id;
if ( $term->term_id != $queried_term_id ){
echo \'<h2>\' . $term->name . \'</h2>\';
echo wpautop( $term->description );
}
$queried_post_ids = array();
foreach ($queried_posts as $post) {
$queried_post_ids[] = $post->ID;
}
unset($post);
$childposts = array();
$child_post_ids = array();
$posts_to_return_ids = array();
if( $term_children ){
$childposts = array();
$child_post_ids = array();
$posts_to_return_ids = array();
foreach ($term_children as $queried_term_child) {
$term_child = get_term_by(\'id\', $queried_term_child, $taxonomy );
if( $term_child->count > 0 ){
$args = array(
\'post_type\' => \'bk_menu\',
\'nopaging\' => true,
\'tax_query\' => array(
array(
\'taxonomy\' => $taxonomy,
\'field\' => \'id\',
\'include_children\' => true,
\'terms\' => array($queried_term_child)
)
)
);
$childposts = array_merge( $childposts, get_posts( $args ) );
}
}
unset($queried_term_child);
foreach ($childposts as $child_post) {
$child_post_ids[] = $child_post->ID;
}
unset($child_post);
$child_post_ids = array_unique( $child_post_ids );
$posts_to_return_ids = array_diff( $queried_post_ids, $child_post_ids );
} else {
$posts_to_return_ids = $queried_post_ids;
}
if( $posts_to_return_ids ){
$posts_to_return = get_posts( array(
\'post_type\' => \'bk_menu\',
\'nopaging\' => true,
\'post__in\' => $posts_to_return_ids
) );
}
if($posts_to_return){
global $post;
foreach ( $posts_to_return as $post ) {
setup_postdata($post);
?><div class="post"><? the_title(); the_content(); ?></div><?
}
unset($post);
wp_reset_postdata();
}
if($term_children){
foreach ($term_children as $term_child_id) {
$term_child = get_term_by(\'id\', $term_child_id, $taxonomy );
if( $term_child->count > 0 && $term_child->parent == $term->term_id ){
$args = array(
\'post_type\' => \'bk_menu\',
\'nopaging\' => true,
\'tax_query\' => array(
array(
\'taxonomy\' => $taxonomy,
\'field\' => \'id\',
\'include_children\' => true,
\'terms\' => array($term_child_id)
)
)
);
$posts_to_return = get_posts( $args );
show_term_posts( $posts_to_return, $term_child, $taxonomy );
}
}
}
}
show_term_posts( $posts, $queried_term, $queried_taxonomy_name );