Search code examples
phpwordpress

WP query_posts() OR Operator


I need to get posts based on meta_keys.

Currently I have this code

global $wp_query;
$args = array_merge( $wp_query->query_vars, 
        array( 
                'meta_key' => 'conference_start_date',
                'orderby' => 'meta_value'
        ) 
);

In cakePHP one would add an OR condition like so

'conditions' =>  array (
      'OR' => array(
           'meta_key' => 'conference_start_date',
           'meta_key' => 'event_start_date'
       ),
       'orderby' => 'meta_value'

)

How can I do this with WP query_post? ie. adding OR with 'meta_key' => 'event_start_date'

[Answer]

'meta_query' => array(
        'relation' => 'OR',
                array(
                    'key'     => 'conference_start_date',
                    'value'   => $now,
                    'compare' => '>='
                ),
                array(
                    'key' => 'event_start_date',
                    'value'   => $now,
                    'compare' => '>='
                )
        ),
        'orderby' => 'meta_value',
        'order' => 'DESC',

Solution

  • You can use meta_query, for example:

    $args = array(
        'meta_query' => array(
        'relation' => 'OR',
            array(
                'key'     => 'conference_start_date',
                'compare' => 'EXISTS'
            ),
            array(
                'key' => 'event_start_date',
                'compare' => 'EXISTS'
            ),
        ),
    );
    

    You can find more information and examples here: http://codex.wordpress.org/Class_Reference/WP_Query