我写了这个函数,只是在 checkout 页面上增加了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, '' );
        }
    }
}

推荐答案

自从WooCommerce 3以来,您使用的代码有点过时了.

下面的代码将从特定的购物车项目计算小计(excluding some defined products)添加一个百分比的费用:

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

代码位于您的子主题的unctions.php文件中(或在插件中).经过测试,效果良好.

Php相关问答推荐

从WooCommerce Checkout Country Select2下拉列表中重新排序国家/地区

在AJAX请求后,Laravel重定向.(不允许使用方法)

基于不用于变体的产品属性隐藏多个WooCommerce发货方式

WooCommerce在购买后多次重定向

FlySystem v3:使用本地适配器时出现问题

启用 WooCommerce 我的帐户付款方式,允许客户添加付款方式

如果在 APIPlatform 3.1 中的同一资源上使用处理器,Messenger 将无法工作

根据小计向 WooCommerce Checkout 添加佣金

如何正确判断 PHP 是否已正确配置为使用 DOMDocument?

PHP - 计算非数值数组

将Shopware 6后端中定义的值导入MultiFilter

使用 PHP 正则表达式从仅包含具有现有顺序的顶级标签的 XML 文档中搜索和创建数组

PHP / DOM : 解析 HTML 以提取基于类的数​​据

如何在不解压缩/重新压缩的情况下连接(连接)两个缩小的值

为什么 8.0 之前的 PHP 版本拒绝命名空间Random\Namespace作为无效语法?

即使密码匹配,密码处理程序也会返回错误

如何将文件直接上传到 Cloudinary 而不先保存在 public 文件夹中

如何简化 php API 中的格式化数组列表数据以提供 React Native 部分列表

检测字符串是否包含Letter with Tilde或Letter + Combining Tilde

无法按今天加上 7 天显示数据库项目