Zak
Zak

Reputation: 23

Change WordPress search to produce WooCommerce search results only

I would like:

http://www.gadgetgogo.co.uk/?s=ipod

to return as:

http://www.gadgetgogo.co.uk/?s=ipod&post_type=product

So when using searches (slider banner and default WordPress search) it produces the second URL.

Upvotes: 1

Views: 4368

Answers (4)

Praveen Patel
Praveen Patel

Reputation: 31

I was looking for similar solution as you but couldn't find any and at last I combined last few answers that I read here and got this working fine as I wanted.

Add below code in your theme's functions.php file

    function wpb_change_search_url() {
    if ( is_search() && ! empty( $_GET['s'] ) && ($_GET['post_type'] != 'product') ) {
        wp_redirect( home_url( "/?s=" ) . urlencode( get_query_var( 's' ) ) . "&post_type=product" );
        exit();
    }   
}
add_action( 'template_redirect', 'wpb_change_search_url' );

hope it will help you and others.

Upvotes: 3

Bence Szalai
Bence Szalai

Reputation: 922

Apparently current WooCommerce versions only consider a search query a product search (and render using the appropriate template), if $query->is_post_type_archive( 'product' ) is true, so the key is to set not only the post_type, but the is_post_type_archive property as well, and to do it before WooCommerce loads its filter (default priority of 10), so with a priority of 9 or smaller.

Example to add into funtions.php:

function my_search_filter($query) {
    if ( $query->is_search && ! is_admin() ) {
        $query->set( 'post_type', 'product' );
        $query->is_post_type_archive = true;
    }
}
add_filter('pre_get_posts','my_search_filter', 9);

Please note, that this code will override all searches as product serach, so if you have other searches as well, implement appropriate checks at the begining of my_search_filter.

Upvotes: 2

dipmala
dipmala

Reputation: 2011

This can be done using pre_get_posts filter. Add below code in your theme's functions.php file

    add_filter( 'pre_get_posts', 'search_by_product_only' );

    function search_by_product_only( $query ) {

        // check if search query only
        if ( $query->is_search ) {
            $query->set( 'post_type', array( 'product') ); // here you can add multiple post types in whcih you want to search
        }

        return $query;
    }

Upvotes: -1

aidinMC
aidinMC

Reputation: 1436

Just add this line to top of search.php

$_GET['post_type'] = 'product'

Upvotes: -1

Related Questions