检查WooCommerce用户角色和支付网关,以及它们是否匹配-收取费用 [英] Check WooCommerce User Role and Payment Gateway and if they match - Apply fee
问题描述
如果选择了特定的支付网关,我将努力向一系列用户角色收取费用。
I'm struggling with applying a fee for an array of user roles if and when a specific payment gateway is selected.
我编写的代码效果很好如果我不检查用户角色,但是一旦尝试了就不会。
The code I've written works fine if I do not check the user role, but once I try and do that, it does not.
我已删除(评论)用户角色 if
语句中的代码,我正在寻求帮助使其正常工作。
I've removed (commented) the user role if
statement in the code and I'm asking for help making it work.
我需要检查用户角色是否与我的角色匹配数组
,如果有,请检查支付网关。如果付款网关也匹配,请收取费用。
I need to check if the user role match my array
and if it does, check the payment gateway. If the payment gateway match too, apply the fee.
这是我的代码:
add_action( 'woocommerce_cart_calculate_fees', 'custom_fee', 20, 1 );
function custom_fee ($cart){
if (is_admin() && !defined('DOING_AJAX')) return;
if (!is_user_logged_in()) return;
if (!is_checkout() && !is_wc_endpoint_url()) return;
$customer_role = wp_get_current_user();
$roles_to_check = array( 'vendor', 'external' );
$payment_method = WC()->session->get('chosen_payment_method');
// if (!in_array($roles_to_check, $customer_role->roles)) return;
if ('bacs' == $payment_method){
$payment_fee = $cart->subtotal * 0.05;
$cart->add_fee( 'Payment Fee', $payment_fee, true );
}
}
推荐答案
您可以使用以下解释,并在代码中添加注释:
You could use the following, explanation with comments added in the code
此代码中必须满足的条件是:
Conditions that must be met in this code are:
- 仅适用于某些用户角色
- 检查付款方式
function custom_fee( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) )
return; // Only checkout page
if ( ! is_user_logged_in())
return;
// Get current WP_User Object
$user = wp_get_current_user();
// User roles
$roles = ( array ) $user->roles;
// Roles to check
$roles_to_check = array( 'vendor', 'external', 'administrator' );
// Compare
$compare = array_diff( $roles, $roles_to_check );
// Result is empty
if ( empty ( $compare ) ) {
// Payment method
$payment_method = WC()->session->get('chosen_payment_method');
// Condition equal to
if ( $payment_method == 'bacs' ) {
// Calculate
$payment_fee = $cart->subtotal * 0.05;
// Add fee
$cart->add_fee( 'Payment Fee', $payment_fee, true );
}
}
}
add_action( 'woocommerce_cart_calculate_fees', 'custom_fee', 10, 1 );
编辑
要完成我的回答,请参阅@
To complete my answer, see the answer from @LoicTheAztec
这篇关于检查WooCommerce用户角色和支付网关,以及它们是否匹配-收取费用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!