试图在WooCommerce checkout 时按5%乘以小计的比例增加佣金.但是,我得到的只是一个空白页面,网站停止工作.

This is the code:

add_action( 'woocommerce_cart_calculate_fees', 'add_commission', 10, 1 ); 
function add_commission( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    // global, is this needed?
    global $woocommerce;

    // get the cart subtotal
    $subtotal = WC()->cart->get_cart_subtotal();

    // commission fee of 5%
    $commission_fee = 0.05;
    
    // the total commission is the 5% multiplied by the subtotal
    $total_commission = $commission_fee * $subtotal;

    // apply the commission
    $cart->add_fee( 'Commission', $total_commission, true );
}

推荐答案

主要错误在get_cart_subtotal()方法中,它是您试图与浮点数相乘的格式化购物车小计HTML(一个字符串).

相反,您应该使用get_subtotal()方法(non formatted subtotal without taxes amount).

所以正确的代码是:

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

    // get the cart subtotal
    $subtotal = $cart->get_subtotal();

    // commission fee of 5%
    $commission_fee = 0.05;
    
    // the total commission is the 5% multiplied by the subtotal
    $total_commission = $commission_fee * $subtotal;

    // apply the commission
    $cart->add_fee( 'Commission', $total_commission, true );
}

Php相关问答推荐

在AJX请求中使用简写后,FormData出现非法调用错误

Laravel数据表在一个视图中传递两个实例

PHP:PHP手册-Manual

如何修复警告:当使用WordPress get_the_Terms()时,Foreach()参数必须是ARRAY|OBJECT类型?

在WooCommerce产品变体SKU字段旁边添加自定义输入字段

在Laravel中为表添加前缀,以将它们逻辑地分组

设置WordPress最近的帖子小部件按修改日期排序

Rappasoft Datatables V2(我想在另一个表具有相同值列时显示数据)

按类别层次 struct 过滤 Laravel 集合

关于Laravel缓存出现的错误

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

尽管有use指令,PHP 类在其他文件中仍处于可见状态

带有分类术语数组的 WordPress Elementor 自定义查询 - 如何要求所有术语都在返回的帖子中

根据页面的最后修订日期设置 MediaWiki 内部链接的样式

注册命名空间后如何获取xml node 值?

在WooCommerce单产品页面中显示特价产品的节省金额

按前 3 列对二维数组中的行数据进行分组,然后用逗号连接每组中的其余列

使用php删除数组中相同数字的所有变体

如何限制for循环php中的条目数

使用 splat 运算符时按引用传递 (...)