Skip Navigation

[Resolved] Filtering with AND + OR

This support ticket is created 5 years, 1 month ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

This topic contains 1 reply, has 2 voices.

Last updated by Christian Cox 5 years, 1 month ago.

Assisted by: Christian Cox.

Author
Posts
#1358035
filter.jpg

Hi,

we want to optimize the filter of some views so that certain fields operate with an AND link and some with an OR link.
Is this possible? (see the screenshot)

Best regards
Uwe

#1358291

Hello, unfortunately when combining custom field filters you can only choose "AND" or "OR" once as a single operator among all custom fields. Complex combinations of AND/OR aren't currently available. It might be possible with custom code using our Views API filters, but that requires fairly advanced knowledge of PHP. We have documentation about manipulating the query with wpv_filter_query available here: https://toolset.com/documentation/programmer-reference/views-filters/#wpv_filter_query

Here's an example that shows how to set the meta_query with a combination of nested AND/OR relations and predefined custom field filter values. Your case will be more complex because it looks like you have implemented front-end filters for a custom search. Unfortunately I don't have any code snippets available for that type of View, and it's a bit outside the scope of what we can offer here in the support forums.

add_filter('wpv_filter_query', 'complex_and_or_query', 199, 3);
function complex_and_or_query($query_args, $view_settings, $view_id ) {
  $view_ids = array( 123, 456 );
  if( in_array( $view_id, $view_ids)) {
    $query_args['meta_query'] = array(
      'relation' => 'OR',
      array(
        'relation' => 'AND',
        array(
          'key' => 'wpcf-city',
          'value' => 'Miami'
        ),
        array(
          'key' => 'wpcf-state',
          'value' => 'Ohio'
        ),
      ),
      array(
        'relation' => 'AND',
        array(
          'key' => 'wpcf-city',
          'value' => 'Augusta'
        ),
        array(
          'key' => 'wpcf-state',
          'value' => 'Maine'
        )
      )
    );
  }
  return $query_args;
}

This example was adapted from the example here:
https://make.wordpress.org/core/2014/10/20/update-on-query-improvements-in-4-1/