在 WooCommerce 中通过 Url 变量 (GET) 申请费用

Apply a fee via Url variable (GET) in WooCommerce

我正在尝试将“add_fee”值传送到查看订单页面,但它不起作用。

我需要启用我的结帐页面以等待 url 参数“getfee”。

如果 getfee 等于 2,则添加费用。

如果没有,则不要添加任何内容。

这是我的代码:

add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge() {
    global $woocommerce;

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;
    
    $fee = $_GET["getfee"];

    if( $fee == "2") {
        $percentage = 0.01;
        $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;    
        $woocommerce->cart->add_fee( 'Surcharge', $surcharge, true, '' );
    }
}

到目前为止,它在结帐页面添加了费用,但是在查看订单时,它没有出现。

我想这可能是因为结帐页面没有该参数但不确定。

如有任何帮助,我们将不胜感激。

您需要在 WC 会话变量中设置您的 Url 费用以避免此问题:

// Get URL variable and set it to a WC Session variable
add_action( 'template_redirect', 'getfee_to_wc_session' );
function getfee_to_wc_session() {
    if ( isset($_GET['getfee']) ) {
        WC()->session->set('getfee', esc_attr($_GET['getfee']));
    }
}

// Add a percentage fee
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
function woocommerce_custom_surcharge( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $fee = WC()->session->get('getfee'); // Get WC session variable value

    if( $fee == "2") {
        $percentage = 0.01;
        $surcharge = ( $cart->cart_contents_total + $cart->shipping_total ) * $percentage;
        $cart->add_fee( 'Surcharge', $surcharge, true, '' );
    }
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。