Support

Account

Home Forums General Issues An advanced meta_query looking for multiple custom field values

Helping

An advanced meta_query looking for multiple custom field values

  • I have two custom fields:

    1) custom_field (text field)
    2) custom_checkbox (checkbox)

    I don’t want posts to be returned if A) custom_field is NOT filled in, or B) if custom_checkbox is ticked.

    So far I have successfully achieved this with the following custom query:

    
                $meta_query = array(
                    'meta_query' => array(
                    array(
                        'key' => 'custom_field',
                        'value'   => '',
                        'compare' => 'NOT IN'
                    ), array(
                        'key' => 'custom_checkbox',
                        'value'   => true,
                        'compare' => 'NOT LIKE'
                )));    
                $query->set('meta_query', $meta_query);
                $query->set( 'posts_per_page',-1 );
            }

    However, I now have two more fields to throw into the equation:

    1) custom_field_2
    2) custom_checkbox_2

    I now don’t want posts to be returned if A) both custom_fields are NOT filled in, or B) if both custom_checkboxes are ticked.

    For example, if custom_checkbox is ticked but custom_checkbox2 is not, I’d still like the post to be returned. And vice versa.

    But if both checkboxes are ticked, that post should not be returned.

    Any guidance much appreciated.

  • Hi @jack1,

    I believe you can use this query:

    $meta_query = array(
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'relation' => 'AND',
                array(
                    'key' => 'custom_field',
                    'value'   => '',
                    'compare' => 'NOT IN'
                ),
                array(
                    'key' => 'custom_field2',
                    'value'   => '',
                    'compare' => 'NOT IN'
                ),
            ),
            array(
                'relation' => 'AND',
                array(
                    'key' => 'custom_checkbox',
                    'value'   => true,
                    'compare' => 'NOT LIKE'
                ),
                array(
                    'key' => 'custom_checkbox2',
                    'value'   => true,
                    'compare' => 'NOT LIKE'
                ),
            ),
        ),
    );    
    

    To learn more about meta_query, please take a look at this page: https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters

    I hope this helps.

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

The topic ‘An advanced meta_query looking for multiple custom field values’ is closed to new replies.