I’m a bit stuck with a WP_Query code. Here it is :
$args = array(
'post_type' => 'post',
'meta_query'=> array(
'key' => 'karma',
'compare' => '>=',
'value' => 0,
'type' => 'numeric'),
'posts_per_page' => 9,
'meta_key' => 'karma',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'post__not_in' => $dont_show_me
);
What I want to do :
Show all posts with karma >= 0 (it works fine with this code). BUT if there are posts with karma = 100 only show 3 of them + the rest of posts.
Examples : 9 posts with karma = 150, 133, 100, 100, 100, 100, 100, 33, 11.
I want to show: 150, 133, 100, 100, 100, 33, 11. (Only 3 posts with karma = 100 are allowed).
Do you have any idea how to achieve this?
Maybe a add_filter('posts_where');
?
UPDATE: Okay I got it working, based on @s_ha_dum answer. It’s a bit tricky, but the result works 😉
$args = array(
// Check for 9 last posts with karma = 100
'post_type' => 'post',
'meta_query'=> array(
array(
'key' => 'karma',
'compare' => '=',
'value' => 100,
'type' => 'numeric'
)
),
'posts_per_page' => 9,
'meta_key' => 'karma',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'post__not_in' => $dont_show_me
);
$karma_qry = new WP_Query($args);
if (!empty($karma_qry->posts)) {
$i = 0;
foreach ($karma_qry->posts as $p) {
$i++;
// Check for more than 3 posts with karma = 100
// Add them in the $dont_show_me array
if($i > 3){
$dont_show_me[] = $p->ID;
}
}
}
// Setup the final query that excluded addional posts with karma = 100
$args['meta_query'][0]['compare'] = '>=';
$args['meta_query'][0]['value'] = 0;
$args['post__not_in'] = $dont_show_me;
$wp_query = new WP_Query($args);