在 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 fee
1个回答
1
投票

您使用的代码自 WooCommerce 3 以来有点过时。

以下代码将从计算小计的特定购物车商品中添加百分比费用(不包括某些定义的产品)

add_action( 'woocommerce_cart_calculate_fees', 'add_checkout_fee_for_gateway', 10, 1 );
function add_checkout_fee_for_gateway( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) 
        return;

    // Only on checkout page and for specific payment method ID
    if ( is_checkout() && ! is_wc_endpoint_url() 
    && WC()->session->get('chosen_payment_method') === 'paypal' ) {
        // Here below define the product IDs to be excluded
        $excluded_product_ids = array(15, 18);
        $percentage_rate      = 0.09; // Defined percentage rate
        $custom_subtotal      = 0; // Initializing
        
        // Loop through cart items
        foreach( $cart->get_cart() as $item ) {
            // Calculate items subtotal from non excluded products
            if( ! in_array($item['product_id'], $excluded_product_ids) ) {
                $custom_subtotal += (float) $item['line_subtotal'];
            }
        }

        if ( $custom_subtotal > 0 ) {
            $cart->add_fee( __('9% value added tax'), ($custom_subtotal * $percentage_rate), true, '' );
        }
    }
}

代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。

© www.soinside.com 2019 - 2024. All rights reserved.