Adding custom taxonomy to search results
-
I am developing a WordPress theme for mobile review website on a localhost and want to modify the search functionality by adding custom post type and custom taxonomy to the search results. The code is working fine for the custom post types, but I am facing issues with the custom taxonomy as it returns no results when search is made using custom taxonomy.
I have manually registered the custom taxonomy with the name of “mobile-brand” which has the different brands like Apple, Samsung etc. as the sub-categories.
Following is my code written in functions.php file for implementation of this task. But, it is not giving me the desired output.
Thanks in advance for the help.
function custom_search_query( $query ) {
if ( $query->is_search && !is_admin() ) {
// Include custom post types in search
$query->set( 'post_type', array( 'post', 'page', 'mobile' ) );
// Get the search term
$search_term = get_search_query();
if ( ! empty( $search_term ) ) {
// Search in the custom taxonomy (mobile-brand)
$tax_query = array(
array(
'taxonomy' => 'mobile-brand', // Custom taxonomy
'field' => 'name',
'terms' => $search_term,
),
);
// Set the taxonomy query in the main query
$query->set( 'tax_query', $tax_query );
}
}
}
add_action( 'pre_get_posts', 'custom_search_query' );
- You must be logged in to reply to this topic.