gpt4 book ai didi

php - 根据 WooCommerce 中的特定付款方式添加费用

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:02:25 25 4
gpt4 key购买 nike

在 WooCommerce 中,我需要为特定支付网关应用自定义手续费。我从这里得到这段代码:How to Add Handling Fee to WooCommerce Checkout .

这是我的代码:

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

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

$fee = 5.00;
$woocommerce->cart->add_fee( 'Handling', $fee, true, 'standard' );
}

此函数为所有交易添加费用。

是否可以调整此功能并使其仅适用于特定的付款方式?

另一个问题是我希望将此费用应用于购物车。可能吗?

我也欢迎任何替代方法。我知道类似的“基于支付网关的费用”woo 插件,但我买不起。

最佳答案

2021 年更新

注意:所有付款方式仅在结帐页面上可用。

以下代码将根据所选的付款方式有条件地添加特定费用:

// Add a custom fee (fixed or based cart subtotal percentage) by payment
add_action( 'woocommerce_cart_calculate_fees', 'custom_handling_fee' );
function custom_handling_fee ( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;

$chosen_payment_id = WC()->session->get('chosen_payment_method');

if ( empty( $chosen_payment_id ) )
return;

$subtotal = $cart->subtotal;

// SETTINGS: Here set in the array the (payment Id) / (fee cost) pairs
$targeted_payment_ids = array(
'cod' => 8, // Fixed fee
'paypal' => 5 * $subtotal / 100, // Percentage fee
);

// Loop through defined payment Ids array
foreach ( $targeted_payment_ids as $payment_id => $fee_cost ) {
if ( $chosen_payment_id === $payment_id ) {
$cart->add_fee( __('Handling fee', 'woocommerce'), $fee_cost, true );
}
}
}

您需要以下内容来刷新付款方式更改的结帐,以使其正常工作:

// jQuery - Update checkout on payment method change
add_action( 'woocommerce_checkout_init', 'payment_methods_refresh_checkout' );
function payment_methods_refresh_checkout() {
wc_enqueue_js( "jQuery( function($){
$('form.checkout').on('change', 'input[name=payment_method]', function(){
$(document.body).trigger('update_checkout');
});
});");
}

代码进入事件子主题(或事件主题)的 functions.php 文件。测试和工作。

How to find a specific payment method ID in WooCommerce Checkout page?

The following will display on checkout payment methods the payment Id just for admins:

add_filter( 'woocommerce_gateway_title', 'display_payment_method_id_for_admins_on_checkout', 100, 2 );
function display_payment_method_id_for_admins_on_checkout( $title, $payment_id ){
if( is_checkout() && ( current_user_can( 'administrator') || current_user_can( 'shop_manager') ) ) {
$title .= ' <code style="border:solid 1px #ccc;padding:2px 5px;color:red;">' . $payment_id . '</code>';
}
return $title;
}

Code goes in functions.php file of your active child theme (or active theme). Once used, remove it.

enter image description here


类似的回答:

关于php - 根据 WooCommerce 中的特定付款方式添加费用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38382278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com