Search code examples
phpwordpresswoocommerceprintfcart

Display different text labels for WooCommerce payment method fees using sprintf


This is based on Assign a percentage fee to WooCommerce payment methods based on user roles. I would like to expand this to display another custom description before the "card fee" label in the sprintf function. I would like to display $description then "Card Fee" then (Percentage Fee).

add_action('woocommerce_cart_calculate_fees', 'sm_credit_card_fee_role_gateway' );
function sm_credit_card_fee_role_gateway( $cart ){
    if ( is_admin() && !defined('DOING_AJAX') )
        return;

    // Only on checkout page and logged in users
    if ( ! ( is_checkout() && ! is_wc_endpoint_url() ) || ! is_user_logged_in() )
        return;

    $wpuser_object = wp_get_current_user();
    $allowed_roles = array('administrator', 'default_wholesaler', 'wholesaler-non-vat-registered', 'shop_manager');

    if ( array_intersect($allowed_roles, $wpuser_object->roles) ){
        $payment_method = WC()->session->get('chosen_payment_method');

        if ( 'cardgatecreditcard' === $payment_method ){
            $percentage = 8.25;
            $description = 'Credit';
        }
        elseif ( 'cardgatesofortbanking' === $payment_method ){
            $percentage = 6;
            $description = 'SofortBanking';
        }
        elseif ( 'cardgategiropay' === $payment_method ){
            $percentage = 3.15;
            $description = 'GiroPay';
        }
        elseif ( 'cardgateideal' === $payment_method ){
            $percentage = 2.1;
            $description = 'iDeal';
        }
    }
    if ( isset($percentage) ) {
        $surcharge = ($cart->cart_contents_total + $cart->shipping_total) * $percentage / 100;
        $cart->add_fee( sprintf( __(' $description Card Fee (%s)', 'woocommerce'), $percentage . '%' ), $surcharge, true );
    }
}


Solution

  • Just replace the following code line:

    $cart->add_fee( sprintf( __(' $description Card Fee (%s)', 'woocommerce'), $percentage . '%' ), $surcharge, true );
    

    with:

    $cart->add_fee( sprintf( __('%s Card Fee (%s)', 'woocommerce'), $description, $percentage . '%' ), $surcharge, true );
    

    Tested and works