【问题标题】:Add a discount when defined products are WooCommerce cart当定义的产品是 WooCommerce 购物车时添加折扣
【发布时间】:2020-10-24 19:33:33
【问题描述】:

我正在尝试为两种产品都在购物车中时设置折扣,无论其他产品也在那里。

到目前为止,只需要数组中的两个之一。

add_action( 'woocommerce_cart_calculate_fees', 'discount_for_ab_products' );
function discount_for_ab_products( $cart ) {

$product_ids = array(34,35);

    foreach ($product_ids as $product_id => $product) {

    $product_cart_id = WC()->cart->generate_cart_id( $product );
    $product_ab_in_cart = WC()->cart->find_product_in_cart( $product_cart_id );

    if ( $product_ab_in_cart ) {
        
        $discount = $cart->subtotal * 0.1;

        $cart->add_fee( __( 'Discount', 'woocommerce' ) , -$discount );
        }
    }
}

【问题讨论】:

    标签: php wordpress woocommerce cart discount


    【解决方案1】:

    请尝试以下方法,当所有定义的产品 ID 都在购物车中时(在您的情况下为两个),这将产生折扣:

    add_action( 'woocommerce_cart_calculate_fees', 'x_products_discount' );
    function x_products_discount( $cart ) {
        // Settings below
        $product_ids = array(34, 35); // <== Your defined product Ids
        $percentage  = 10; // <== discount in percentage (10% here)
    
        $found_ids   = array();
        
        // Loop through cart items
        foreach (WC()->cart->get_cart() as $cart_item ) {
            // Loop through defined product Ids
            foreach( $product_ids as $product_id ) {
                if( in_array( $product_id, array( $cart_item['product_id'], $cart_item['variation_id'] ) ) ) {
                    $found_ids[$product_id] = $product_id;
                    break;
                }
            }
        }
        
        // Discount part
        if( count( $found_ids ) === count( $product_ids ) ) {
            $cart->add_fee( __( 'Discount', 'woocommerce' ), -( $cart->subtotal * $percentage / 100 ) );
        }
    }
    

    代码在您的活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      • 2022-12-20
      • 1970-01-01
      • 1970-01-01
      • 2019-06-28
      • 2014-11-21
      • 2020-09-01
      相关资源
      最近更新 更多