Search code examples
phpwoocommercehook-woocommercecheckoutpayment-method

Change payment method title for specific products in WooCommerce checkout


I'm trying that, when a specific product is in the checkout, the title of the payment method changes from; for example: "Payment by card" to "Payment in parts", is it possible?

I have tried with jquery:

jQuery(function($){
    if ( $('#payment-fractional-payment').length ){
        $("label[for='payment_method_redsys_gw']").text("Payment in installments");
    }
});

but it only changes it for a moment and returns to the default title, is there any way to do it in the functions.php with some hook?


Solution

  • You can use this simple hooked function, where you will have to set the correct targeted payment id and the targeted product id(s):

    add_filter( 'woocommerce_gateway_title', 'change_payment_gateway_title', 100, 2 );
    function change_payment_gateway_title( $title, $payment_id ){
        $targeted_payment_id  = 'redsys_gw'; // Set your payment method ID
        $targeted_product_ids = array(37, 53); // Set your product Ids
    
        // Only on checkout page for specific payment method Id
        if( is_checkout() && ! is_wc_endpoint_url() && $payment_id === $targeted_payment_id ) {
            // Loop through cart items
            foreach( WC()->cart->get_cart() as $item ) {
                // Check for specific products: Change payment method title
                if( in_array( $item['product_id'], $targeted_product_ids ) ) {
                    return __("Payment in installments", "woocommerce");
                }
            }
        }
      return $title;
    }
    

    Code goes in functions.php file of the active child theme (or active theme). It should works.