0

I'm trying to build a wp_query, so far I've managed to get desired result using following query.

$args = array(
    'meta_query' => array(
        'relation' => 'OR',
         array( //check if meta key exists
                'key' => 'youtube-1',
                'compare' => '=',
             ),
             array( //or not exists 
                'key' => 'youtube-1',
                'compare' => 'NOT EXISTS'
             )
        ),
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
);

The problem: I want to check for all youtube meta keys and they are in array form extracted from a foreach loop. For example; array(youtube-1, youtube-2, youtube-3, youtube-4 and so on..)

And ofcourse posts will be ordered by by meta_value_num.

Any tip will be appreciated. Thanks

6
  • You are on path to dark side ;)
    – Sumit
    Commented May 24, 2016 at 6:48
  • And you seem to be happy :/ If I failed I'll be using two loops. First to get post ids and then seconds to order them.
    – wp student
    Commented May 24, 2016 at 6:54
  • No I am not happy ;) But why do you have so many meta keys. Only one meta key with multiple values is the right approach.
    – Sumit
    Commented May 24, 2016 at 8:59
  • I'm making a complex site. These meta keys taxonomy slugs coming from user meta table.
    – wp student
    Commented May 24, 2016 at 9:25
  • I'm not sure what you intend. Are you trying to check if a post has any of the custom fields youtube-1, youtube-2, youtube-3 and so on?
    – Luis Sanz
    Commented May 24, 2016 at 9:26

1 Answer 1

2

The WP_Query() custom field (i.e. meta) query can handle arrays for field values. You just need to add the compare key to your array:

$args = array(
          'numberposts' => -1,
          'post_type' => 'post',
          'meta_query' => array (
            array (
              'key' => 'my_key',
              'value' => 'target_value',
                          'compare' => 'IN'
            )
          ) );      

        $new_query = new WP_Query( $args );
2
  • But we have array of keys here.
    – wp student
    Commented May 24, 2016 at 7:27
  • in array you have key and its value which is compare. The variable $args get the value of your desire result. Make sure before inserting in WP_Query you must have to check what value you get in $args variable by using var_dump.
    – Owais Alam
    Commented May 24, 2016 at 7:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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