Support » Developing with WordPress » Use an array for the meta_query ‘key’ argument

  • meyertreestone

    (@meyertreestone)


    I need to list all posts that have have a meta_a value of the_post_id or meta_b value of the_post_id. I find that the following code does it:

    'meta_query'     => array(
      array(
         'key'   => array('meta_a','meta_b'),
         'value' => get_the_ID(),
      ),
    ),
    

    However, the documentation at https://developer.wordpress.org/reference/classes/wp_meta_query/ suggests that ‘key’ must be a string. Therefore I am hesitant to use this code since it seems to only work by chance. Can anyone clarify if it is valid to use an array for ‘key’ instead of string.

Viewing 6 replies - 1 through 6 (of 6 total)
  • Joy

    (@joyously)

    I think it should have a ‘relation’ of ‘OR’ since the default is ‘AND’, and have two separate arrays.
    See the example at https://developer.wordpress.org/reference/classes/wp_meta_query/#comment-1989

    cb4242

    (@cb4242)

    What Joy said. I have used this on one of my sites and it is easy and works well.

    Thread Starter meyertreestone

    (@meyertreestone)

    Thanks and @joyously and @cb4242 for your input. As per your suggestions, I went with:

    'meta_query'     => array(
     'relation' => 'OR',
      array(
         'key'   => 'meta_a'
         'value' => get_the_ID(),
      ),
      array(
         'key'   => 'meta_b'
         'value' => get_the_ID(),
      ),
    ),

    But it would still be nice to know if
    'key' => array('meta_a','meta_b')
    is valid.

    cb4242

    (@cb4242)

    According to the WP_Meta_Query documentation, the key must be a string. (So no, an array would not work.)

    meta_key (string) – Custom field key. ( You must sanitize this yourself )

    Thread Starter meyertreestone

    (@meyertreestone)

    I understand, but when I tried it with an array, it did work! The WordPress source code supports an array but the documentation does not reflect that fact. Which is correct, the code, or the documentation?

    Joy

    (@joyously)

    You can open a docs ticket, to make them match. We get a lot of those.
    https://core.trac.wordpress.org/

Viewing 6 replies - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.