根据 Woocommerce 中的产品类型收取额外费用

Additional fees based on product type in Woocommerce

如果产品类型是 "auction",我想做的是在结帐页面添加并显示新费用。我的代码存在的问题是显示了新费用但未添加到总费用中。

我用过这个代码 并使用此功能对其进行自定义:

add_action( 'woocommerce_calculate_totals', 'action_cart_calculate_totals', 10, 1 );
function action_cart_calculate_totals( $cart_object ) {
    if ( (is_admin() && ! defined( 'DOING_AJAX')) || WC()->cart->is_empty() )
        return;
    foreach ( WC()->cart->cart_contents as $key => $values ) {
        if ( $values['data']->get_type() == 'auction' ) {           
            $buyerfee  = 0.10; // auction buyer fee
            $surcharge = $cart_object->cart_contents_total * $buyerfee;
            $cart_object->add_fee( 'Auction Fee (10%)', $surcharge, true, '' );
        }
    }
}

在这种情况下,您需要使用 woocommerce_cart_calculate_fees 操作挂钩:

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

    $is_auction = false;
    foreach ( $cart_object->cart_contents as $item ) {
        if ( $item['data']->is_type( 'auction' ) ) {
            $is_auction = true;
            break;
        }
    }
    if( $is_auction ){
        $percent  = 10; // auction buyer fee (in percetage)
        $fee = $cart_object->cart_contents_total * $percent / 100;
        $cart_object->add_fee( "Auction Fee ($percent%)", $fee, true );
    }
}

代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件。

代码已经过测试并且可以工作