sc2015
sc2015

Reputation: 141

Show WooCommerce Products in get_search_query()

I'm using Divi WP theme and I have the following code in my header:

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

                <?php

                    printf( '<input type="search" class="et-search-field" placeholder="%1$s" value="%2$s" name="s" title="%3$s" />',

                        esc_attr__( 'Search &hellip;', 'Divi' ),

                        get_search_query(),

                        esc_attr__( 'Search for:', 'Divi' )

                    );

                ?>

                </form>

I need to display WooCoomerce products in the search results as well as pages and posts.

I tried adding:

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

But in doing so it now only shows WooCommerce products and no longer shows pages/posts.

Thanks

Upvotes: 0

Views: 1886

Answers (1)

Benoti
Benoti

Reputation: 2210

You need to use the pre_get_posts filter

function search_filter($query) {
    if ( !is_admin() && $query->is_main_query() ) {
        if ($query->is_search) {

            $query->set('post_type', array('post', 'product'));

            $meta_query = array(
                'relation' => 'AND',
                array(
                    'key' => '_visibility',
                    'value' => 'visible',
                    'compare' => 'IN'
                ),
                array(
                    'key' => '_stock_status',
                    'value' => 'instock',
                    'compare' => '='
                )
            );

            $query->set('meta_query', $meta_query);
        }
    }
}

add_action('pre_get_posts','search_filter');

Add this in functions.php of the child-theme, of course you can remove or add any post type in the array defining post_type (page, coupon). To be sure to retrieve only available products, we need to set a special meta_query according to Woocommerce custom fields.

Hope its helps!

Upvotes: 2

Related Questions