Include custom fields value in woocommerce search

|▌冷眼眸甩不掉的悲伤 提交于 2020-03-22 07:21:24

问题


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?


回答1:


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




回答2:


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

  • https://wordpress.stackexchange.com/a/309900/133615

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



来源:https://stackoverflow.com/questions/49496211/include-custom-fields-value-in-woocommerce-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!