当定义的产品是WooCommerce购物车时添加折扣

时间:2020-07-04 06:49:48

标签: php wordpress woocommerce cart discount

无论购物车中同时有其他什么产品,我都在为两种产品都在购物车中设置折扣。

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

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 );
        }
    }
}

1 个答案:

答案 0 :(得分:0)

请尝试以下方法,当所有定义的产品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文件中。经过测试,可以正常工作。