Check WooCommerce User Role and Payment Gateway and if they match - Apply fee

♀尐吖头ヾ 提交于 2020-07-21 06:37:15

问题


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.

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.

This is my code:

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 );
    }
}

回答1:


You could use the following, explanation with comments added in the code

Conditions that must be met in this code are:

  • only for certain user roles
  • checks on payment method
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 );


来源:https://stackoverflow.com/questions/62079374/check-woocommerce-user-role-and-payment-gateway-and-if-they-match-apply-fee

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!