Skip Navigation

[Resolved] View filter: posts ARE in one taxonomy term but EXCLUDE if in another term

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
- 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Hong_Kong (GMT+08:00)

This topic contains 1 reply, has 2 voices.

Last updated by Luo Yang 5 years, 1 month ago.

Assisted by: Luo Yang.

Author
Posts
#1400101

Hi

I am building a site with a custom post type of "pubs" linked to a custom taxonomy "category" (hierarchical not flat)

In custom category taxonomy I have:
Recommended
Information
Closed
Archived

A pub can be in multiple categories - for example it can be recommended but also closed, or an information pub that is also archived. Some pubs are simply in a single category.

I want to build a view that filters on "information pubs that are not archived" but I can't for the life of me work out how to do it. I've read the documentation, played around with the and, in not in, operators but it doesn't seem to let me have a filter where I select a term it MUST HAVE alongside a term is MUST NOT HAVE.

Am I missing something? or should I approach this in a different way with multiple custom taxonomies??

many thanks for your help - I couldn't find any support tickets in the forums that answered this question either

#1400367

Hello,

Thanks for the details, within Views GUI, you can only one filter on same taxonomy "category", in your case you need two filters on taxonomy "category", so it needs custom codes, for example:
1) Setup your post view, filter by:
Select posts with taxonomy:
Categories in one of these: Information

2) Add below PHP codes into your theme file functions.php:

add_filter('wpv_filter_query', function($query, $settings, $views_id){
	if($views_id == 123){
		$query['tax_query'] = isset($query['tax_query'])?$query['tax_query']:array();
		foreach($query['tax_query'] as $k => $v){
			if(isset($v['taxonomy']) && $v['taxonomy'] == 'category'){
				$arr = array(
					'relation' => 'AND',
					$v,
					array(
						'taxonomy' => 'category',
						'field'    => 'slug',
						'terms'    => array( 'archived' ),
						'operator' => 'NOT IN',
					)
				);
				$query['tax_query'][$k] = $arr;
			}
		}
	}
	return $query;
}, 99, 3);

Please replace 123 with your post view's ID
replace "category" with your custom taxonomy "category" slug

More help:
https://toolset.com/documentation/programmer-reference/views-filters/#wpv_filter_query
https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters