WordPress & Woocommerce 独立站启用SKU搜索功能

a purple and white square with the word woo on it
Posted by: Fengjiajun Comments: 0

WordPress & Woocommerce 独立站启用SKU搜索功能

默认情况,woocommerce产品模块的SKU属性是不参与前台的搜索功能,【如果有的话那就说明你用的模版已经解决了这个问题】,以下代码可以修复这个问题:

// 启用woocommerce的SKU搜索功能
function search_by_sku( $search, $query_vars ) {
    global $wpdb;
    if ( isset( $query_vars->query['s'] ) && !empty( $query_vars->query['s'] ) ) {
        $search_sku = $query_vars->query['s'];
        $args = array(
            'posts_per_page' => -1,
            'post_type'      => array('product', 'product_variation'),
            'meta_query'     => array(
                array(
                    'key'     => '_sku',
                    'value'   => $search_sku,
                    'compare' => 'LIKE'
                )
            )
        );
        $posts = get_posts( $args );
        if ( empty( $posts ) ) return $search;
        $get_post_ids = array();
        foreach ( $posts as $post ) {
            if ( $post->post_type == 'product_variation' ) {
                $get_post_ids[] = $post->post_parent;
            } else {
                $get_post_ids[] = $post->ID;
            }
        }
        if ( sizeof( $get_post_ids ) > 0 ) {
            $search = str_replace( 'AND (((', "AND ((({$wpdb->posts}.ID IN (" . implode( ',', array_unique($get_post_ids) ) . ")) OR (", $search );
        }
    }
    return $search;
}
add_filter( 'posts_search', 'search_by_sku', 999, 2 );