Search filter by custom taxonomy using pre_get_posts
-
I’m working on a (what I thought would be) basic search filtering, using a custom taxonomy “Resource Type”. I have a set of radio buttons that allow you to select which taxonomy to filter by, in the search form.
<input name="resource-type" type="radio" value="12" id="cat-product-manual"><label for="cat-product-manual">Product Manuals</label> <input name="resource-type" type="radio" value="10" id="cat-faqs"><label for="cat-faqs">FAQs</label> <input name="resource-type" type="radio" value="11" id="cat-videos"><label for="cat-videos">Videos</label>
I set up a filter on ‘pre_get_posts’ that will modify the query with the custom taxonomy. Just for testing purposes I hardcoded one of the IDs in:
function my_search_filter($query) { if ($query->is_search) { $taxquery = array( array( 'taxonomy' => 'resource-type', 'field' => 'id', 'terms' => 10 ) ); $query->set( 'tax_query', $taxquery ); } return $query; } add_filter('pre_get_posts','my_search_filter', 1);
Which works great.
However as soon as I start to work in my resource-type selections things get weird. It looks like I can access resource-type either by using
$_GET['resource-type']
or
$query->query['resource-type']
I can echo out either of those inside my function, and I get the correct values (even though I get a ‘headers already sent’ error when I do that, but at least I know the values are coming through correctly).
However, if I use either of those in an “if” statement, or try to insert the values into the taxonomy query, it no longer works.
function my_search_filter($query) { if ($query->is_search) { $type = $query->query['resource-type']; if (isset($type)) { $taxquery = array( array( 'taxonomy' => 'resource-type', 'field' => 'id', 'terms' => $type ) ); $query->set( 'tax_query', $taxquery ); } } return $query; } add_filter('pre_get_posts','my_search_filter', 1);
With that code, the tax_query does not get added to the query. Anything I try to add to the query within that “if” statement doesn’t work. So the filter is not applied and I get all results. And if I remove the “if” statement, the code runs again, but doesn’t get the value of the $type variable. It just comes through as null and I get no results.
Is there something I’m missing here? Am I going about this the wrong way? This one has me baffled. Thanks in advance for any help you could give!
- The topic ‘Search filter by custom taxonomy using pre_get_posts’ is closed to new replies.