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

标签 woocommerce product cart

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

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

或者,如果他们有多个类别的商品,则只需随机选择两个即可。

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

最佳答案

以下代码自动返 repo 物车中产品中属于该产品类别的 $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 表示全部,这可以根据您的需求进行调整


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

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 - 如何根据产品类别在 WooCommerce 中自动设置交叉销售,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61158160/

相关文章:

php - 显示 WooCommerce 迷你购物车中的商品数量

php - WooCommerce:管理员中的动态自定义结帐字段

mysql - SQL条件if不存在

php - 根据自定义产品属性值过滤 Woocommerce 产品

php - 为 WooCommerce 单个产品页面设置第二个价格标签

php - 在 Woocommerce 中购买某个产品类别的产品时重定向

php - 如何使用 foreach 从购物车函数创建(或插入到 MySQL 中)单个订单 ID

php - 使用自定义值预归档结帐邮政编码

php - 根据产品类型向产品价格添加自定义文本标签

java - 尝试使用向导导出 Eclipse 产品时出错