为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕田峪4524236 2023-10-22 21:28:09
我正在创建高级 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,如何添加?
查看完整描述

1 回答

?
HUX布斯

TA贡献1876条经验 获得超6个赞

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,如何添加?


查看完整回答
反对 回复 2023-10-22
  • 1 回答
  • 0 关注
  • 64 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信