[+] Change Views checkboxes filter to compare with AND instead of OR

A checkboxes custom field used as a View search filter uses an OR comparison (return posts matching any of the checked values) rather than an AND comparison (return posts matching all checked values), and this can only be changed by modifying the underlying query.

Use the following snippet to switch to an AND comparison. You will need to edit the checkboxes field slug and the View ID(s) you want this to apply to.

/**
 * Modify View query filters for checkboxes custom field filter
 * to compare with AND instead of default OR
 */

function tssupp_mod_checkboxes_query($view_args, $view_settings, $view_id)
{
    $slug = 'colours'; // Edit slug
    $metakey = 'wpcf-'.$slug;

    if (in_array($view_id, array( 88 ))) { // Edit View ID(s)

        $meta_query_keys = array_keys($view_args['meta_query']);
        unset($meta_query_keys['relation']);
        foreach ($meta_query_keys as $meta_query_key){
            if ( is_array( $view_args['meta_query'][$meta_query_key] ) && isset($view_args['meta_query'][$meta_query_key][0]['key']) && $view_args['meta_query'][$meta_query_key][0]['key'] == $metakey ){
                $view_args['meta_query'][$meta_query_key]['relation'] = 'AND';
            }
        }
    }

    return $view_args;
}
add_filter('wpv_filter_query', 'tssupp_mod_checkboxes_query', 101, 3);

Let us know if this snippet is not working for you:

This snippet doesn’t work
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments