Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #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

    #1442318

    i 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');
    #1442319

    there 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;
    });
    #1442434

    Thanks for this – it kind of works..

    When I enter a search term into the search bar, it will display results from everywhere like this:

    View post on imgur.com

    If I click enter, then it will only display products like this:

    View post on imgur.com

    I really want to just display products in the first example too..

    Is this possible?

    #1442495

    Hi,

    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

Viewing 5 posts - 1 through 5 (of 5 total)
  • You must be logged in to reply to this topic.