如何在WooCommerce中根据产品类别自动设置交叉销售 [英] How to automatically set cross-sells in WooCommerce based on product category

查看:19
本文介绍了如何在WooCommerce中根据产品类别自动设置交叉销售的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例如,有人添加了女装类别的商品,那么它将在交叉销售部分展示同一类别的其他产品。

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

有没有办法做到这一点,或者必须逐个查看每种产品才能选择交叉销售的产品?

推荐答案

以下代码自动从购物车中的产品返回属于产品类别的$cross_sellsID。

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表示全部,可根据您的需要进行调整


限制('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 );

这篇关于如何在WooCommerce中根据产品类别自动设置交叉销售的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆