如何根据产品类别在 WooCommerce 中自动设置交叉销售

How to automatically set cross-sells in WooCommerce based on product category

我正在尝试在 WooCommerce 中编辑购物车页面的交叉销售部分。我想在交叉销售部分显示来自同一类别的随机产品。

例如,某人添加了女装类别中的商品,然后它会在交叉销售部分显示同一类别中的其他产品。

或者如果他们有来自多个类别的项目,那么只需随机选择两个。

有没有办法做到这一点,或者是否必须单独检查每个产品才能 select 交叉销售产品?

以下代码 returns 自动 $cross_sells 属于购物车中产品类别的 ID。

function filter_woocommerce_cart_crosssell_ids( $cross_sells, $cart ) {
    // Initialize
    $product_cats_ids = array();
    $product_cats_ids_unique = array();

    foreach ( $cart->get_cart() as $cart_item ) {       
        // Get product id
        $product_id = $cart_item['product_id'];

        // Get current product categories id(s) & add to array
        $product_cats_ids = array_merge( $product_cats_ids, wc_get_product_term_ids( $product_id, 'product_cat' ) );
    }

    // Not empty
    if ( !empty( $product_cats_ids ) ) {
        // Removes duplicate values
        $product_cats_ids_unique = array_unique( $product_cats_ids, SORT_REGULAR );

        // Get product id(s) from a certain category, by category-id
        $product_ids_from_cats_ids = get_posts( array(
            'post_type'   => 'product',
            'numberposts' => -1,
            'post_status' => 'publish',
            'fields'      => 'ids',
            'tax_query'   => array(
                array(
                    'taxonomy' => 'product_cat',
                    'field'    => 'id',
                    'terms'    => $product_cats_ids_unique,
                    'operator' => 'IN',
                )
            ),
        ) );

        // Removes duplicate values
        $cross_sells = array_unique( $product_ids_from_cats_ids, SORT_REGULAR );
    }

    return $cross_sells;
}
add_filter( 'woocommerce_cart_crosssell_ids', 'filter_woocommerce_cart_crosssell_ids', 10, 2 );

注: 'numberposts' => -1表示ALL,这个可以根据自己的需要进行调整


限制 ('posts_per_page') 可以通过 woocommerce_cross_sells_total 过滤器钩子设置

function filter_woocommerce_cross_sells_total( $limit ) {
    // Set limit
    $limit = 4;
    
    return $limit;
}
add_filter( 'woocommerce_cross_sells_total', 'filter_woocommerce_cross_sells_total', 10, 1 );