Home › Forums › General Issues › 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?
I would go through and update the posts so that all your data is consistent. This will optimize the DB query.
Thanks, that’s what I figured – any suggestions on the best way to do that?
This is a manual operation which you will have to spend some time to edit and save the posts via the wp-admin
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.
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.
The topic ‘Multiple fields in a meta_query’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
Are you building WordPress sites with ACF and @BeaverBuilder, and wanted to use your ACF Blocks in both the block editor and Beaver Builder?— Advanced Custom Fields (@wp_acf) May 10, 2023
The BB team recently added support for using ACF Blocks in Beaver Builder. Check it out 👇https://t.co/UalEIa5aQi
© 2023 Advanced Custom Fields.