I need help creating a query that displays posts from custom post type and every 4 posts, display 4 posts that contains a taxonomy of the same post
Should I do two different queries? Normal taxonomy:
$args = array(
'post_type' => 'news',
'posts_per_page' => -1,
);
$news = new WP_Query($args);
Taxonomy query:
$args = array(
'post_type' => 'news',
'offset' => 4,
'tax_query' => array(
array(
'taxonomy' => 'news-category',
'field' => 'slug',
'terms' => 'the-community',
),
),
);
$community = new WP_Query($args);
I don't know how to iterate to get the query I want
CodePudding user response:
You'll need to use iteration in your loop. Then inside that loop run another query to loop the second group of posts each time the iteration counter is evenly divisible by 4 using modulo operator. Offset that second query each time it runs by dividing the iteration counter by 4.
I haven't test the following code to be functional, but conceptually it should be valid.
[Edited]
$args = array(
'post_type' => 'news',
'posts_per_page' => -1,
);
$news = new WP_Query($args);
// Get Loopy
if ( $news->have_posts() ) {
$i = 0; // Set iteration to 0
while ( $news->have_posts() ) {
$news->the_post();
$i ; // Increment iteration counter
// News post output
echo the_title();
// Check if iteration counter is evenly divisible by 4 using the modulo operator (%).
if ( $i % 4 == 0 ) {
$posts_per_page = 4;
// Get your offset.
$offset = $i - $posts_per_page;
$args = array(
'post_type' => 'news',
'posts_per_page' => $posts_per_page,
'offset' => $offset,
'tax_query' => array(
array(
'taxonomy' => 'news-category',
'field' => 'slug',
'terms' => 'the-community',
),
),
);
$community = new WP_Query($args);
while ( $community->have_posts() ) {
$community->the_post();
// Community post output
echo the_title();
}
}
}