嗯,这是一条旧线索,但如果有人像我一样路过,这可能会有所帮助。我们的想法是修改主查询,这样我们就不需要使用模板并生成新的查询和循环。。。
PS:尚待在大型数据库中测试。我的情况令人满意。
function grouped_by_taxonomy_main_query( $query ) {
if ( $query->is_home() && $query->is_main_query() ) { // Run only on the homepage
$post_ids = array();
$terms = get_terms(\'my_custom_taxonomy\');
foreach ( $terms as $term ) {
$post_ids = array_merge( $post_ids, get_posts( array(
\'posts_per_page\' => 4, // as you wish...
\'post_type\' => \'my_custom_post_type\', // If needed... Default is posts
\'fields\' => \'ids\', // we only want the ids to use later in \'post__in\'
\'tax_query\' => array( array( \'taxonomy\' => $term->taxonomy, \'field\' => \'term_id\', \'terms\' => $term->term_id, )))) // getting posts in the current term
);
}
$query->query_vars[\'post_type\'] = \'my_custom_post_type\'; // Again, if needed... Default is posts
$query->query_vars[\'posts_per_page\'] = 16; // If needed...
$query->query_vars[\'post__in\'] = $post_ids; // Filtering with the post ids we\'ve obtained above
$query->query_vars[\'orderby\'] = \'post__in\'; // Here we keep the order we generated in the terms loop
$query->query_vars[\'ignore_sticky_posts\'] = 1; // If you dont want your sticky posts to change the order
}
}
// Hook my above function to the pre_get_posts action
add_action( \'pre_get_posts\', \'grouped_by_taxonomy_main_query\' );