skip to Main Content

I was trying to change the label of WooCommerce Payments from "Popular payment methods" to something else on the checkout page.

I added this snippet to functions.php of the child theme

add_filter( 'woocommerce_gateway_title', 'change_payment_gateway_title', 100, 2 );
function change_payment_gateway_title( $title, $payment_id ){
    if( $payment_id === 'woocommerce_payments' ) {
        $title = __("custom text", "woocommerce");
    }
    return $title;
}

and this

add_filter( 'woocommerce_gateway_title', 'change_payment_gateway_title' );
function change_payment_gateway_title( $payment_id ){
    return str_replace( 'Popular payment methods', 'custom text', $payment_id );
}

They both work for a fraction of a second when the checkout page is still loading, but the title jumps back to the original text ("Popular payment methods") when the page has finished loading. They work without any problem for other payment methods though.

Is there anything wrong with my code?

2

Answers


  1. add_filter( 'woocommerce_gateway_title', 'change_payment_gateway_title', 25, 2 );
    
    function change_payment_gateway_title( $title, $gateway_id ){
        
        if( 'gateway_id' === $gateway_id ) {
            $title = 'By Cash or Credit Card on delivery';
        }
    
        return $title;
    }
    

    What is $gateway_id and where to get it? I think the easiest way is to use this code snippet which adds a payment gateway ID column in WooCommerce settings.

    Login or Signup to reply.
  2. The original text getting restored originates from the js variable "wcpay_config" that is created by woocommerce payments. It is contained in the key "checkoutTitle" and passed through wp_localize_script.
    Because I didn’t find a way to hook into this function I used this answer implementing a subclass and your first solution combined, to achieve a full replacement:

    class Filterable_Scripts extends WP_Scripts
    {
        function localize( $handle, $object_name, $l10n ) {
            $l10n = apply_filters( 'script_word_replacements', $l10n, $handle, $object_name );
            return parent::localize($handle, $object_name, $l10n);
        }
    }
    
    add_action( 'init', function() {
        $fscripts = new Filterable_Scripts();
    
        $GLOBALS['wp_scripts'] = $fscripts;
    });
    
    add_filter('script_word_replacements', 'woocommerce_payments_name', 10 , 3);
    
    function woocommerce_payments_name($l10n, $handle, $object_name ) {
        if('wcpay-upe-checkout' == $handle && 'wcpay_config' == $object_name) {
            $l10n[checkoutTitle] = __("Custom name for woocommerce payments", "woocommerce");
        }
        return $l10n;
    }
    

    Also take a look at this answer, if other plugins stop working.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search