5

I tried include custom fields value in woocommerce search but i have a problem.

On Google and Stack too, i saw examples with pre_get_posts, so i thought this is good direction and i made code like this:

function custom_search( $query ) {

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

        if ( $query->is_search() ) { 

            $meta_query = array(
                'key'       => 'custom_color',
                'value'     => $query->query['s'],
                'compare'   => 'LIKE'  
            );

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

        }

    }

}

add_action( 'pre_get_posts' , 'custom_search' );

Unfortunately it's not working. Can You help me?

kanlukasz
  • 1,103
  • 19
  • 34

2 Answers2

4

I see what you did wrong, here is a working example that i did on my own instance.

function custom_search( $query ) {

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

        if ( $query->is_search() ) { 

            $meta_query = $query->get( 'meta_query' );

            $meta_query[] = array(
                'key'       => 'custom_color',
                'value'     => $query->query['s'],
                'compare'   => 'LIKE'  
            );

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

        }

    }

}

add_action( 'woocommerce_product_query' , 'custom_search' );

Since you are using the Woocommerce search woocommerce_product_query would be the correct hook, and to be safe, keeping existing defaults by $query->get( 'meta_query' );

Reference: WooCommerce search products between price range using WP_Query

Thanks OP for bringing me this case :)

Musk
  • 1,477
  • 1
  • 15
  • 25
  • Thank U so much for the answer, but this code works only when i search empty value (like this: ?s=&post_type=product). It's not what i expect or maybe i probably misspelled my question. Here is example for good understand: I have another custom field _codeproduct. (https://pastebin.com/3Brz6Cwn) Products has codes ( example for one product: A0099B ) I would like to search for a product by product code. Is this possible with this method? Or maybe should i open new thread with this problem, because is this completly different case? – kanlukasz Mar 26 '18 at 18:06
  • @Luk well just replacing the `custom_color` by `_codeproduct` should do the trick, i personnaly tried with my pricing key and changed the compare value to equal and it worked. Maybe there is something wrong with the value you are trying to compare with or you are excepting a behavior or result more complex? – Musk Mar 26 '18 at 18:22
2

Here is my similar question from wordpress.stackexchange.com:

That's what I was looking for and it's the right solution

kanlukasz
  • 1,103
  • 19
  • 34