I'm currently showing events on my websites, based on a month they are "tagged" in. For each month I have made a query to display the posts within that month, orderby the date the post expires.
I'm was looking for an easier way (either to combine it to 1 query, instead of multiple) to display (for example) the first 50 posts within all these queries..
The code:
$argsJanuari = [
'numberposts' => -1,
'cat' => '-1',
'order' => 'ASC',
'meta_key' => '_expiration-date',
'orderby' => 'meta_value',
'meta_query' => array(
array(
'key' => 'maand',
'value' => 'Januari 2017',
)
)
];
$loopJanuari = new WP_Query($argsJanuari);
if($loopJanuari->have_posts()) { ?> <h2>Januari 2017</h2> <?php
while($loopJanuari->have_posts()) {
$loopJanuari->the_post();
get_template_part( 'concert-single' );
}
wp_reset_postdata();
}
$argsFebruari = [
'numberposts' => -1,
'cat' => '-1',
'order' => 'ASC',
'meta_key' => '_expiration-date',
'orderby' => 'meta_value',
'meta_query' => array(
array(
'key' => 'maand',
'value' => 'Februari 2017',
)
)
];
$loopFebruari = new WP_Query($argsFebruari);
if($loopFebruari->have_posts()) { ?> <h2>Februari 2017</h2> <?php
while($loopFebruari->have_posts()) {
$loopFebruari->the_post();
get_template_part( 'concert-single' );
}
wp_reset_postdata();
}
$argsMaart = [
'numberposts' => -1,
'cat' => '-1',
'order' => 'ASC',
'meta_key' => '_expiration-date',
'orderby' => 'meta_value',
'meta_query' => array(
array(
'key' => 'maand',
'value' => 'Maart 2017',
)
)
];
$loopMaart = new WP_Query($argsMaart);
if($loopMaart->have_posts()) { ?> <h2>Maart 2017</h2> <?php
while($loopMaart->have_posts()) {
$loopMaart->the_post();
get_template_part( 'concert-single' );
}
wp_reset_postdata();
}
?>
You can combine all queries into one by using the meta query relation. More info on that here: https://codex.wordpress.org/Class_Reference/WP_Meta_Query. Furthermore, to set the number of posts, the post paremeter is called posts_per_page. I am not sure about the one you used, 'numberposts'
, so I have replaced it in the code below.
Anyway, Find below the code with the merged queries and 50 posts shown. It's not tested and written with the thinking that the code you posted above works. Let me know if this helped :)
$argsConcert = [
'posts_per_page' => 50,
'cat' => '-1',
'order' => 'ASC',
'meta_key' => '_expiration-date',
'orderby' => 'meta_value',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'maand',
'value' => 'Januari 2017',
)
array(
'key' => 'maand',
'value' => 'Februari 2017',
)
array(
'key' => 'maand',
'value' => 'Maart 2017',
)
)
];
$loopConcert = new WP_Query($argsConcert);
if($loopConcert->have_posts()) { ?> <h2>Concert 2017</h2> <?php
while($loopConcert->have_posts()) {
$loopConcert->the_post();
get_template_part( 'concert-single' );
}
wp_reset_postdata();
}