Nick Kaloudis
Nick Kaloudis

Reputation: 55

Woocommerce search in custom fields

i have a woocommerce e-shop website. My search is searching only in product title and sku fields. I want to search also in some custom fields (like "_barcode" and "_mpn").

I have this script but when i use it in fuctions.php i can't search by product title.

function search_filter( $query ) {

    $key_fields = array ( '_barcode', '_mpn', '_sku' );
    $value_field = $query->query_vars['s'];
    $query->query_vars['s'] = '';

    if ( $value_field != '' ) {

        $filter_query = array( 'relation' => 'OR' );

        foreach ( $key_fields as $one_field ) {
            array_push ( $filter_query , array (
                'key' => $one_field,
                'value' => $value_field,
                'compare' => 'LIKE'
            ) );
        }
        $query->set( 'meta_query' , $filter_query );
    }
}
add_filter( 'pre_get_posts' , 'search_filter');

Why i can't search the product title when i use this script? Any idea?

Thank you.

Upvotes: 1

Views: 287

Answers (0)

Related Questions