After a few hours and thanks to our comrades around the world, I was able to change the main request, so we don’t even need to go through the templates and generate new requests and loops ...
function grouped_by_taxonomy_main_query( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$post_ids = array();
$terms = get_terms('formato');
foreach ( $terms as $term ) {
$post_ids = array_merge( $post_ids, get_posts( array(
'posts_per_page' => 4,
'post_type' => 'video',
'fields' => 'ids',
'tax_query' => array( array( 'taxonomy' => $term->taxonomy, 'field' => 'term_id', 'terms' => $term->term_id, ))))
);
}
$query->query_vars['post_type'] = 'video';
$query->query_vars['posts_per_page'] = 16;
$query->query_vars['post__in'] = $post_ids;
$query->query_vars['orderby'] = 'post__in';
$query->query_vars['ignore_sticky_posts'] = 1;
}
}
add_action( 'pre_get_posts', 'grouped_by_taxonomy_main_query' );
source
share