How can I change my search form to bring up product results, not blog results

by Jakob Cross   Last Updated September 21, 2018 14:08 PM

I'm currently building a wordpress/woocommerce site using a template, and am having issues with the search form & results.

When using the search bar, results come up with the title 'blog', and display as blog results instead of product.

Any advice will be greatly appreciated

Search.php file:

<div class="ps-search">

<div class="ps-search__content">
    <a class="ps-search__close" href="#">
        <span></span>
    </a>

    <form class="ps-form--search-2" method="get" action="<?php echo esc_url( home_url( '/' ) ); ?>">
        <h3>

            <?php if(class_exists('Woocommerce')):?>

                <?php esc_html_e('Search products...');?>

            <?php else:?>

                <?php esc_html_e('Search posts...');?>  

            <?php endif;?>  

        </h3>

        <div class="form-group">

            <input class="form-control" type="text" name="s" placeholder="<?php esc_attr_e('Enter keyword here...', 'xuper');?>" value="<?php echo esc_attr(get_search_query());?>">

            <?php if(class_exists('Woocommerce')):?>

                <input type="hidden" name="post_type" value="product">

            <?php endif;?>  

            <button type="submit" class="ps-btn ps-btn--black ps-btn--fullwidth btn-search-popup">
                <?php esc_html_e('Search', 'xuper');?>
            </button>

        </div>

    </form>

</div>



Answers 1


Try below filter in your function.php file

function SearchFilter($query) {
if ($query->is_search) {
$query->set('post_type', 'product');
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');

Hope this will help!

Pratik Patel
Pratik Patel
September 21, 2018 13:26 PM

Related Questions


Wordpress Multi-Step Product Search

Updated April 12, 2017 12:08 PM

Book Search Form for Wordpress

Updated August 25, 2016 08:05 AM

Risk of sql injection for custom search form

Updated February 23, 2017 23:08 PM

How to exclude pages from the search results

Updated March 14, 2017 05:08 AM