SearchWP

Version 4 Documentation

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.