It is possible to search for posts with a specific term by appending the URL with:
?&term=abc
Is it possible to do the opposite and search excluding a specific term? Something like:
?&term=NOTabc
It is possible to search for posts with a specific term by appending the URL with:
?&term=abc
Is it possible to do the opposite and search excluding a specific term? Something like:
?&term=NOTabc
You must be logged in to post a comment.
The basic explanation
is_search()
to determin if you’re on a search page or not.get_search_template()
which basically is a wrapper function forget_query_template('search')
.locate_template()
, which checks for file existence and then does aload_template()
.$wp_query->query_vars
get checked and the$_template_file
gets extracted and loaded.A note before about the query var …
WordPress uses the query var
s
to save the searched term into its query. If you’re running a custom query string, then you need to modify theget_search_query
filter like the following:Some solution(s)
We now have different possible solutions:
The easy solution
Runs in the template and better fits for excluding taxonomy terms.
A) Get all posts in the template loop, check every post in the loop for every (taxonomy) term 1) and then exclude/don’t show it.
In you loop in your template search.php file:
This is just an example of the loop.
The sophisticated solution(s)
Runs before running the actual main query and suits better for excluding terms in general.
B.1) Filter the term out of of the search template query.
In the following example I use the
posts_clauses
filter to show you that you can modify even more with just one filter (do avar_dump
of the$pieces
array for more insights). You could also use theposts_where
filter, which runs before the clauses filter.B.2) Filter the term out of of the search template query _in a more performant & specific way.
In the following example I use the
posts_search
filter to show you how you can modify thewhere
clause only for the search query. It’s pretty much the same as theposts_where
filter.Footnotes:
1) You haven’t been clear if it’s about a search or a taxonomy term.
Very detailed and thorough answer @kaiser has posted above. I wanted to use first method, however looks like that the first method’s function used in Current wp 4.7 does not work.
We have to use other function WordPress has that is called:
has_term
instead ofis_object_in_taxonomy
to check for specific terms in taxonomy assigned to current post.Here is final code which worked for me by using
has_term
function in your search.php any custom page template you are using for search results, in my case it skips property listings from the search if the listing status is SOLD or RENTED: