How can I exclude posts with a specific custom field and value with this query?
$my_query = new WP_Query( $args = array(
// It should be in the first category of our post:
'category__in' => array( $st_cat ),
// Our post should NOT be in the list:
'post__not_in' => array( $post->ID ),
'posts_per_page' => 8,
'orderby' => 'desc',
));
I already tried this without sucess:
$my_query = new WP_Query( $args = array(
// It should be in the first category of our post:
'category__in' => array( $st_cat ),
// Our post should NOT be in the list:
'post__not_in' => array( $post->ID ),
'posts_per_page' => 8,
'orderby' => 'desc',
//extra code added without sucess
'meta_query' => array(
'key' => 'city',
'value' => 'true',
'compare' => 'NOT LIKE',
)
));
How can I exclude posts with a specific custom field and value with this query?
$my_query = new WP_Query( $args = array(
// It should be in the first category of our post:
'category__in' => array( $st_cat ),
// Our post should NOT be in the list:
'post__not_in' => array( $post->ID ),
'posts_per_page' => 8,
'orderby' => 'desc',
));
I already tried this without sucess:
$my_query = new WP_Query( $args = array(
// It should be in the first category of our post:
'category__in' => array( $st_cat ),
// Our post should NOT be in the list:
'post__not_in' => array( $post->ID ),
'posts_per_page' => 8,
'orderby' => 'desc',
//extra code added without sucess
'meta_query' => array(
'key' => 'city',
'value' => 'true',
'compare' => 'NOT LIKE',
)
));
Share
Improve this question
edited Oct 28, 2019 at 20:42
RiddleMeThis
3,8078 gold badges22 silver badges30 bronze badges
asked Oct 28, 2019 at 20:15
bpybpy
2995 silver badges20 bronze badges
2
- Keep in mind that you always want to query the database for what you want for performance reasons. The moment you start telling it what you don't want, the scalability and speed of your site goes out the window. It might sound like a reasonable thing to say "I want everything except this post", but behind the scenes the DB server is constructing a brand new table with every single post ( except that one ) every single time you make that query, then running the rest of the query on it. What you've asked for could easily bring down a large site with 3-4 active visitors – Tom J Nowell ♦ Commented Oct 28, 2019 at 20:52
- Instead, wouldn't it be better to store a field that's the inverse and search for that instead? Or filter it out in PHP ( this can be thousands of times faster on some sites ) – Tom J Nowell ♦ Commented Oct 28, 2019 at 20:53
2 Answers
Reset to default 2The meta_query argument takes an array of arrays.
'meta_query' => array(
array(
'key' => 'city',
'value' => 'true',
'compare' => 'NOT LIKE',
)
)
Perhaps something like this can work:
if ( !$query->is_admin && $query->is_search) {
$query->set('post__not_in', array(36,33));
$query->set('meta_query',
array('relation' => 'OR',
array('key' => 'city',
'value' => 'true',
'compare' => 'NOT EXISTS'),
));
}
return $query;