Search code examples
phpwordpressloops

Wordpress Meta Query to pull posts with empty meta value for custom fields


I am trying to pull custom post type with field value set as 'No' or not set (older posts for which this custom field is not set). The code i am using for query args is:

$args = array_merge( $wp_query->query_vars, array( 'post_type' => 'com', 'meta_query' => array(
        'relation' => 'OR',
        array(
            'key' => 'ct_Featured_C_radio_3292',
            'value' => 'No',
            'compare' => 'LIKE'
        ),
        array(
           'key' => 'ct_Featured_C_radio_3292',
           'value'   => array(''),
            'compare' => 'LIKE'
        )
    )));

But this meta query only pulls posts with value set as 'No' and not with posts with empty values. Please advice on how to write the meta query so all posts with No and empty values can be pulled.


Solution

  • "NOT EXISTS" checks will include meta_keys that don't exist.

    $args = array_merge(
      $wp_query->query_vars, 
      array(
        'post_type' => 'com',
        'meta_query' => array(
          'relation' => 'OR',
          array(
            'key' => 'ct_Featured_C_radio_3292',
            'value' => 'No',
            'compare' => 'LIKE'
          ),
          array(
            'key' => 'ct_Featured_C_radio_3292',
            'compare' => 'NOT EXISTS'
          )
        )
      )
    );