1

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',
    )
));
  • 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 Oct 28 '19 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 Oct 28 '19 at 20:53
1

The meta_query argument takes an array of arrays.

'meta_query' => array(
    array(
        'key' => 'city',
        'value' => 'true',
        'compare' => 'NOT LIKE',
    )
)
| improve this answer | |
  • if I add your code to mine bellow //extra code added without sucess, it removes all my posts – bpy Oct 28 '19 at 20:30
0

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;
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.