SearchWP Documentation

View the installation guide, browse the Knowledge Base, find out about SearchWP’s many hooks

Limiting Results to a Specific Taxonomy Term (Category, Tag, etc)

Apply to native/default search results

If instead of creating a search form to allow choosing a Category (or other Taxonomy Term) you would instead like to:

Always limit your native/default search results to a specific Category we can use a \SearchWP\Mod like so:

<?php
// Limit SearchWP Native/Default results to Category that has 'foobar' slug.
add_filter( 'searchwp\native\args', function( $args, $query ) {
if ( ! isset( $args['tax_query'] ) || ! is_array( $args['tax_query'] ) ) {
$args['tax_query'] = [];
}
$args['tax_query'][] = [
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'foobar',
];
return $args;
}, 20, 2 );

Note that this \SearchWP\Mod applies to all Native/Default searches.

Programmatic search query

If instead of creating a search form to allow choosing a Category (or other Taxonomy Term) you would instead like to:

Always limit a search query to a specific Taxonomy Term (in this case Category) programmatically

We can use the tax_query parameter of SWP_Query like so:

All hooks should be added to your custom SearchWP Customizations Plugin.

<?php
// Limit SearchWP results to Category that has 'foobar' slug.
$search = new \SWP_Query( [
's' => 'coffee', // Search string.
'tax_query' => [ [
'taxonomy' => 'category',
'field' => 'slug',
'terms' => 'foobar',
] ],
] );
// Print all results.
print_r( $search->posts );

The tax_query can accommodate multiple conditions in the same way WP_Query works.

Create a Better WordPress Search Experience Today

Never lose visitors to unhelpful search results again. SearchWP makes creating your own smart WordPress search fast and easy.

Get SearchWP Now
Multiple Search Engines Icon