如何通过 id 从增加功能中的额外费用中排除 woocommerce 产品

问题描述 投票:0回答:1

我编写此函数是为了在结帐页面上的网关上添加 9% 的额外费用。 **现在我想按 ID 从增加功能中的额外费用中排除某些产品。 ** 我怎样才能用最少的代码更改来简单地做到这一点?

add_action( 'woocommerce_cart_calculate_fees', 'add_checkout_fee_for_gateway' );
function add_checkout_fee_for_gateway() {
    // Check if we are on the checkout page
    if ( is_checkout() ) {
        global $woocommerce;
        $chosen_gateway = $woocommerce->session->chosen_payment_method;
        if ( $chosen_gateway == 'paypal' ) {
            $percentage = 0.09;
            
            /* for all products prices + shipping (total price)
            $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
            */
            
            $surcharge = ( $woocommerce->cart->get_subtotal() ) * $percentage;
            $woocommerce->cart->add_fee( '9% value added tax', $surcharge, true, '' );
        }
    }
}
php wordpress woocommerce hook-woocommerce
1个回答
0
投票

根据提供的代码,实现使用产品Id排除产品的功能,免收额外费用,可以查看以下代码。

add_action( 'woocommerce_cart_calculate_fees', 'add_checkout_fee_for_gateway', 10, 1 );
function add_checkout_fee_for_gateway( $cart ) {
    if ( is_checkout() ) {
        global $woocommerce;
        $chosen_gateway = $woocommerce->session->chosen_payment_method;
        if ( $chosen_gateway == 'paypal' ) {
            $percentage = 0.09;
        
            /* The product Id of products, which need to be excluded from additional fees, should be put in this "$excluded_products" array, for example, $excluded_products = array(1, 2, 3, 4); */
            $excluded_products = array();
            $surcharge_product_subtotal = 0;
            foreach ( $cart->get_cart_contents() as $cart_item ) {
                $product_id = $cart_item['product_id'];
                if( !in_array( $product_id, $excluded_products ) ) {
                      $product = $cart_item['data'];
                      $surcharge_product_subtotal = $surcharge_product_subtotal + $cart->get_product_subtotal( $product, $cart_item['quantity'] );
                }
            }            
            if( $surcharge_product_subtotal > 0 ) {        
                $surcharge = $surcharge_product_subtotal * $percentage;
                $woocommerce->cart->add_fee( '9% value added tax', $surcharge, true, '' );
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.