-
AuthorPosts
-
May 4, 2024 at 3:51 pm #1442292
Hi,
Is there a way to modify the results returned by the search function?
We run an eCommerce store and only want results returned for products and not blogs and terms and conditions for example..
Thanks,
Harvinder
May 5, 2024 at 6:32 am #1442318i use this snippet to include some custom post types to the search:
try:
function wc_only_search_filter_pages($query) { // Frontend search only if ( ! is_admin() && $query->is_search() ) { $query->set('post_type', 'product'); $query->set( 'wc_query', 'product_query' ); } return $query; } add_filter('pre_get_posts','wc_only_search_filter_pages');
May 5, 2024 at 6:42 am #1442319there are pages that use a slightly different snippet – if the last snippet is not what you want.
I think it’s more accurate what is allowed to be displayed in the search results:
( of course – such snippets are intended for the child-theme functions.php. )add_filter( 'pre_get_posts', function( $query ) { global $woocommerce; if ( ! is_admin() && $query->is_search && isset( $query->query_vars['s'])){ $query->set( 'post_type', 'product' ); $query->set( 'wc_query', 'product_query' ); $tax_query = $query->get( 'tax_query' ) ?: []; $tax_query[] = [ 'taxonomy' => 'product_visibility', 'field' => 'slug', 'terms' => 'exclude-from-search', 'operator' => 'NOT IN' ]; $query->set( 'tax_query', $tax_query ); } return $query; });
May 6, 2024 at 11:41 am #1442434Thanks for this – it kind of works..
When I enter a search term into the search bar, it will display results from everywhere like this:
If I click enter, then it will only display products like this:
I really want to just display products in the first example too..
Is this possible?
May 7, 2024 at 3:26 am #1442495Hi,
Thank you for the screenshots.
For the search bar or AJAX search, please add this filter in the functions.php file:
add_filter('avf_ajax_search_query', 'avf_ajax_search_query_mod', 10, 1); function avf_ajax_search_query_mod( $search_parameters ) { $defaults = array('numberposts' => 5, 'post_type' => array( 'product' ), 'post_status' => 'publish', 'post_password' => '', 'suppress_filters' => false); $_REQUEST['s'] = apply_filters( 'get_search_query', $_REQUEST['s']); $search_parameters = array_merge( $defaults, $_REQUEST ); return $search_parameters; }
Best regards,
Ismael -
AuthorPosts
- You must be logged in to reply to this topic.