Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include custom fields value in woocommerce search

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?

like image 484
kanlukasz Avatar asked Mar 26 '18 16:03

kanlukasz


People also ask

How do I create a custom field searchable in WordPress?

In your chosen section, find the 'Add/Remove Attributes' button and give it a click. In the popup that appears, click to open the 'Custom Fields' dropdown menu. One option is to select 'Any Meta Key' which will make all your custom fields searchable.

How do I save custom field data in WordPress?

Adding Custom Fields in WordPressClick on the Add Custom Field button to save it. You can edit this custom field any time you want and then click on the update button to save your changes. You can also delete it as needed. Now you can save your post to store your custom field settings.


1 Answers

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 :)

like image 198
Musk Avatar answered Oct 02 '22 05:10

Musk