Support

Account

Home Forums General Issues Multiple fields in a meta_query

Solved

Multiple fields in a meta_query

  • Hi, I’m trying to query multiple custom fields in a meta_query like:

    
    'meta_query' => array(
        array(
            'key' => 'field1',
            'value' => '1',
        ),
        array(
            'key' => 'field2',
            'value' => '0',
        ),
    ),
    

    Which works fine, but because field2 is a new field and isn’t populated on most posts, the query doesn’t show any results so I have to query for NULL and FALSE . The only way to do this is to change the meta_query relationship to OR and query field2 twice, which also means I can’t query field1 effectively anymore:

    
    'meta_query' => array(
        'relation' => 'OR'
        // array(
        //     'key' => 'field1',
        //     'value' => '1',
        // ),
        array(
            'key' => 'field2',
            'value' => '',
            'compare' => 'NOT EXISTS',
        ),
        array(
            'key' => 'field2',
            'value' => '0',
        ),
    ),
    

    Is there a way around this? Should I be updating all my existing posts with the new value first before querying for them?

  • Hi @jmh

    I would go through and update the posts so that all your data is consistent. This will optimize the DB query.

    Thanks
    E

  • Thanks, that’s what I figured – any suggestions on the best way to do that?

  • Hi @jmh

    This is a manual operation which you will have to spend some time to edit and save the posts via the wp-admin

    Thanks
    E

  • Ah, too bad.

    I was wondering if I could do something with update_field() and a custom query for the affected posts, but I was having trouble putting together the final solution. If I’m on the right track, let me know.

    Thanks!

  • Hi @jmh

    Aah, yes, you could write a custom query indeed.
    1. Use get_posts to find all the posts
    2. Use the update_field function to save the value

    Please note that you will need to use the field_key instead of the field_name. The reason for this is explained int he update_field docs, but basically, ACF needs to know which field you have saved the value from.

    Thanks
    E

Viewing 6 posts - 1 through 6 (of 6 total)

The topic ‘Multiple fields in a meta_query’ is closed to new replies.