将 WooCommerce 产品搜索扩展到自定义分类法和自定义字段

我正在创建高级 woocommerce 搜索,我想在搜索查询中添加 sku、product_tag 和 Product_category。下面我使用在 WooCommerce 产品搜索答案代码中启用自定义分类法,从而启用多个分类法的搜索:


add_filter( 'posts_search', 'woocommerce_search_product_tag_extended', 999, 2 );

function woocommerce_search_product_tag_extended( $search, $query ) {

    global $wpdb, $wp;


    $qvars = $wp->query_vars;


    if ( is_admin() || empty($search) ||  ! ( isset($qvars['s'])

    && isset($qvars['post_type']) && ! empty($qvars['s'])

    && $qvars['post_type'] === 'product' ) ) {

        return $search;

    }


    // Here set your custom taxonomies in the array

    $taxonomies = array('product_tag', 'product_cat');


    $tax_query  = array('relation' => 'OR'); // Initializing tax query


    // Loop through taxonomies to set the tax query

    foreach( $taxonomies as $taxonomy ) {

        $tax_query[] = array(

            'taxonomy' => $taxonomy,

            'field'    => 'name',

            'terms'    => esc_attr($qvars['s']),

        );

    }


    // Get the product Ids

    $ids = get_posts( array(

        'posts_per_page'  => -1,

        'post_type'       => 'product',

        'post_status'     => 'publish',

        'fields'          => 'ids',

        'tax_query'       => $tax_query,

    ) );


    if ( sizeof( $ids ) > 0 ) {

        $search = str_replace( 'AND (((', "AND ((({$wpdb->posts}.ID IN (" . implode( ',', $ids ) . ")) OR (", $search);

    }

    return $search;

}

我也想在搜索查询中添加产品 sku,如何添加?


慕田峪4524236
浏览 67回答 1
1回答

HUX布斯

add_filter( 'posts_search', 'woocommerce_search_product_tag_extended', 999, 2 );function woocommerce_search_product_tag_extended( $search, $query ) {    global $wpdb, $wp;    $qvars = $wp->query_vars;    if ( is_admin() || empty($search) ||  ! ( isset($qvars['s'])    && isset($qvars['post_type']) && ! empty($qvars['s'])    && $qvars['post_type'] === 'product' ) ) {        return $search;    }    // Here set your custom taxonomies in the array    $taxonomies = array('product_tag', 'product_cat');    $tax_query  = array('relation' => 'OR'); // Initializing tax query    // Loop through taxonomies to set the tax query    foreach( $taxonomies as $taxonomy ) {        $tax_query[] = array(            'taxonomy' => $taxonomy,            'field'    => 'name',            'terms'    => esc_attr($qvars['s']),        );    }    // Get the product Ids    $ids = get_posts( array(        'posts_per_page'  => -1,        'post_type'       => 'product',        'post_status'     => 'publish',        'fields'          => 'ids',        'tax_query'       => $tax_query,    ) );    if ( sizeof( $ids ) > 0 ) {        $search = str_replace( 'AND (((', "AND ((({$wpdb->posts}.ID IN (" . implode( ',', $ids ) . ")) OR (", $search);    }    return $search;}我也想在搜索查询中添加产品 sku,如何添加?
打开App,查看更多内容
随时随地看视频慕课网APP