Hi there, I am fiddling around with some Views Code to produce a few "How To" technical posts showing how to achieve certain things that Views cannot do out of the box.
One of the classic things is for example this:
- we have few posts tagged with several tags (or taxonomies, or fields, whatever)
- we have a custom front end search by those tags, or taxonomies
- we want to exclude just one of those tags from both the search and the view results.
This could be done with a Query filter but as we know, as soon there is a Custom Search that Query filter will be overwritten by the Custom Search.
So a PHP snippet is needed to exclude our "special tag" from the View results.
Easy enough:
add_filter( 'wpv_filter_query', 'remove_snowflake_tags', 101, 3 );
function remove_snowflake_tags( $query_args, $view_settings, $view_id ) {
$types = (array) $query_args['post_type'];
$working_view = 4024;
$post_type = 'your_post_type';
$query_arg_to_add = 'tag__not_in';
$items_to_exclude = [37];
if ( !is_admin() && in_array( $post_type, $types ) && $view_id == $working_view ) {
$query_args[$query_arg_to_add] = $items_to_exclude;
}
return $query_args;
}
This code will successfully remove Tag ID 37 from the View Results even if we have a Custom Search for Tags.
However, the Custom Search will still show the Tag with ID 37, albeit with a "results count" of 0, since the query returns no posts with that tag.
So, to remove the tag from the actual search input as well, I had to use "Show only filter options that would produce results" in the View search settings.
But, this option has a warning:
"This can have a performance impact."
In WP Grid Builder for example the search inputs options are for example "read" from the results - so we never need to worry about that, we just exclude things from the query and the search inputs will automatically be reflecting that.
What is the best way in Toolset to do the same?
Apart from the obvious setting, which seems to open up potential performance issues (I assume on large amount of posts only, as I saw no problems in my tiny site)
I wasn't sure if there is a WP Views Filter for it, it does not seem so. Or am I missing something?
The very bad thing with all this is, when we have an AJAX view and "Clear all filters" then our tag comes back!
This is kind of not the goal, obviously.
You can see what I mean here hidden link.
You can see there is no dev_tag.
Then you search, and "Clear all filters"
The tag will be back!
Now reload the page, and the tag will be gone again 😉
This is surely not how it is expected to work, I assume there are 2 problems:
First, the query filter PHP code does not change the actual query inputs but only the results (which is the reason why we still see the tag in the search but with result count 0)
Then, if we use AJAX there seems to be an issue with the PHP Filter not being fired at all when we "Clear all filters"
Thanks for any input 🙂