Skip Navigation

[Resolved] Creating a multi-condition AND/OR custom filter in a View

This thread is resolved. Here is a description of the problem and solution.

Problem: I would like to create a complex and/or condition in my View filters, but I can only select one AND/OR clause.

Solution: While it's not possible in wp-admin, you would be able to achieve this type of filter using the wpv_filter_query API:

add_filter( 'wpv_filter_query', 'fix_custom_and_or_query' , 99, 3);
function fix_custom_and_or_query( $query_args, $view_settings, $view_id ) {
    $metaQuery = [];
    if( $view_id == 1234 ) { // change this to the correct View ID
      // uncomment to inspect the selected filters in $_POST or $_GET
      // error_log(print_r($_GET, true));
      // error_log(print_r($_POST, true));
      $someVar = $_GET['wpv-wpcf-some-slug'];
      if($someVar == 'abc') {
        // ** - sample conditional here based on the user-selected filters
      }
 
      // ** - code to create the correct meta query in $metaQuery goes here
 
      // then replace the original meta query with the updated meta query
      $query_args['meta_query'] = $metaQuery;
    }
    return $query_args;
}

Relevant Documentation:

This support ticket is created 6 years, 6 months 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.

No supporters are available to work today on Toolset forum. Feel free to create tickets and we will handle it as soon as we are online. Thank you for your understanding.

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 8 replies, has 2 voices.

Last updated by Christian Cox 6 years, 6 months ago.

Assisted by: Christian Cox.

Author
Posts
#576050

I have a view with these 2 filters:

TYPE (taxonomy filter)
-- Novelty
-- Best Seller

CATEGORY (taxonomy filter)
-- Cat A
-- Cat B
...

I need to be able to filter ANY checked Category, but if I check both Types (Novelty AND Best Seller),
the outcome result should match:

- All products checked as BOTH Type Novelty AND Best Seller
- with ANY of the checked Categories

The AND relationship between TYPE and CATEGORY filters I've managed to do on the views' query interface, but how's the TYPE condition configured in a view?

thanks.

#576095
Screen Shot 2017-10-04 at 9.52.41 AM.png

Hi, when inserting or editing a taxonomy Filter Control in the View editor, you should be able to select a comparison function that will include either ANY or ALL terms selected. See the attached screenshot. You can use this option to specify which you prefer for each taxonomy.

If you cannot see the Filter Control area, you may need to activate it by toggling open the "Screen Options" tab in the top right corner of the editor page in wp-admin.

#576302

Hello Christian,

sorry, but this filter field:

TYPE (taxonomy filter)

is actually a custom field, having two checkboxes, each with a numeric value - not a taxonomy filter...
Given that, is it still possible?
I don't see that kind of AND / OR options for that field, only equal/different/greather than ... that kind of options.

#576620
Screen Shot 2017-10-05 at 12.23.46 PM.png

You only have the ability to make one selection for "AND" vs "OR" with custom field filters, and that selection applies to all the custom field filters unfortunately. This option can be found in the Query Filter editor. If you need to build more complex queries with combinations of "AND" and "OR" conditions, you will need to use custom code to modify the query with PHP. We have a hook available for you to use:
https://toolset.com/documentation/programmer-reference/views-filters/#wpv_filter_query

#577964

Hello Christian,

I'm familiar with filters, but could you give me an usage example for this one, close to the case I've described?

thanks in advance.

#577983

You can find the full documentation for WP meta queries here:
https://codex.wordpress.org/Class_Reference/WP_Meta_Query

I did a quick search for "wordpress complex and or meta query" and found this guy, which contains two groups of relationships using "OR", and each group using "AND" internally:
https://make.wordpress.org/core/2014/10/20/update-on-query-improvements-in-4-1/

$query = new WP_Query( array(
    'meta_query' => array(
        'relation' => 'OR',
        array(
            'relation' => 'AND',
            array(
                'key' => 'city',
                'value' => 'Miami',
            ),
            array(
                'key' => 'state',
                'value' => 'Ohio',
            ),
 
        ),
        array(
            'relation' => 'AND',
            array(
                'key' => 'city',
                'value' => 'Augusta',
            ),
            array(
                'key' => 'state',
                'value' => 'Maine',
            ),
 
        ),
    ),
) );

So you could implement that structure in a wpv_filter_query hook like so:

add_filter( 'wpv_filter_query', 'fix_custom_and_or_query' , 99, 3);
function fix_custom_and_or_query( $query_args, $view_settings, $view_id ) {
    $metaQuery = [];
    if( $view_id == 1234 ) { // change this to the correct View ID
      // uncomment to inspect the selected filters in $_POST or $_GET
      // error_log(print_r($_GET, true));
      // error_log(print_r($_POST, true));
      $someVar = $_GET['wpv-wpcf-some-slug'];
      if($someVar == 'abc') {
        // ** - sample conditional here based on the user-selected filters
      }

      // ** - code to create the correct meta query in $metaQuery goes here

      // then replace the original meta query with the updated meta query
      $query_args['meta_query'] = $metaQuery;
    }
    return $query_args;
}
#578155

Hello Christian,

I've made this experience:

function anets_va_custom_and_or_query( $query_args, $view_settings, $view_id ) {

	$metaQuery = [];

	if (  $view_id == 1671 ) {

		// uncomment to inspect the selected filters in $_POST or $_GET
		//error_log(print_r($_GET, true));
		// error_log(print_r($_POST, true));

		$type = $_GET['wpv-wpcf-produtos-tipo'];
		$category = $_GET[' wpv-category'];

		$args = array(
			'post_type' => 'produto',
			'tax_query' => array(
				array(
					'taxonomy' => 'category',
					'field'    => 'term_id',
					'terms'    => array( 39 ), // specific term, for testing
					'operator' => 'IN'
				),
			),
		);
		$metaQuery = new WP_Query( $args );

		// replace the original meta query with the updated meta query
		$query_args['meta_query'] = $metaQuery;
	}
	return $query_args;
}
add_filter(  'wpv_filter_query', 'anets_va_custom_and_or_query' , 99, 3 );

But it does not seem to affect the result in any way.
The view_id seems to be correct, as some testing inside that condition is triggered.

Can it be due to the fact that we're using Ajax to refresh results (as soon as user changes the filter)?

thanks.

#578170

Hello again,

just got an update from my client and he changed his mind regarding this filter, which considerably reduced its complexity.
So I won't need to solve this right now.
Hope your suggestions so far may help somebody with a similar question.

thanks, Christian.

#578203

Okay understood. For future reference, I think my explanation was a bit unclear. You would need to remove this line:

$metaQuery = new WP_Query( $args );

The actual query will be created later in the request lifecycle, after this function is executed. This function should manipulate and return the $args array, which will be passed in to the WP_Query later. If you want to use the variable name $args, that's fine too, but you would remove the $metaQuery variable since it's no longer needed.

This ticket is now closed. If you're a WPML client and need related help, please open a new support ticket.