Make an array for a query with false conditions

1

I have the following query , where the conditions are informed from a array :

$args = array(
    'post_type'           => 'post',
    'post_status'         => 'publish',
    'orderby'             => 'date',
    'order'               => 'DESC',
    'ignore_sticky_posts' => true,
    'category_name'       => $atts['category_name'],
    'posts_per_page'      => ($atts['number'] > 0) ? $atts['number'] : 
                              get_option('posts_per_page')
 );

 $meta_query[] = array(
    'key'   => '_featured',
    'value' => 'yes' 
 );

 $args['meta_query'] = $meta_query;

 $the_query = new WP_Query($args);

This query brings me the posts which is marked as Featured . But what I need is the reverse, I need the posts that are not Featured . If I only put 'no' instead of 'yes' , in this snippet:

'key'   => '_featured',
'value' => 'yes'

It only returns me the posts that once were featured . But those who never were, do not appear, because they do not even have meta_key featured .

The easiest thing in my view would be to bring the% posts from "featured = yes" , but I do not know how to do it.

    
asked by anonymous 11.10.2017 / 22:04

2 answers

2

In addition to the elements key and value , meta_query supports the comparison operator on the compare element. Try != :

 $meta_query[] = array(
    'key'     => '_featured',
    'value'   => 'yes' ,
    'compare' => '!='
  );

There is a lot of information on this in Codex , and I found a more "chewed" tutorial here . A search for "meta_compare" shows that the possible values are those supported by MySQL:

'=' , '!=' , '>' , '>=' , '<' , '<=' , 'LIKE' , 'NOT LIKE' , 'IN' , 'NOT IN' , 'BETWEEN' , 'NOT BETWEEN' or 'NOT EXISTS'

Since the default is the equality operator 'REGEXP' .

For more information on the utility of each operator, MySQL documentation is very detailed.

    
12.10.2017 / 00:09
0

Thank you guys, it was a lot of help!

The code that worked was as follows:

$meta_query[] = array(
   'relation' => 'OR',
   array (
         'key'   => '_featured',
         'compare' => 'NOT EXISTS'
         ),
   array (
         'key'   => '_featured',
         'value' => 'no' 
         )  
);
    
13.10.2017 / 02:29