I`m trying to make a switch on (COD) cash on delivery label if the delivery option is selected
The user has 2 options on delivery:
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_samedaycourier724" value="samedaycourier:7:24" >
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_samedaycourier15ln" value="samedaycourier:15:LN" checked="checked">
If the value="samedaycourier:15:LN" is checked I want the COD label to be Credit Card on Delivery instead of Cash on Delivery
I copied a similar code and tried to adapt it to my need, unfortunately without the desired result. Any advice?
add_action( 'woocommerce_review_order_before_payment', 'customizing_payment_option', 10, 0 );
function customizing_payment_option(){
$text1 = __( 'Cash on Delivery', 'woocommerce' );
$text2 = __( 'Credit Card on EasyBox', 'woocommerce' );
?>
<script>
jQuery(function($){
// 1. Initialising once loaded
if($('input[name^="shipping_method[0]"]:checked').val() == 'samedaycourier:15:LN' )
$('input[id^="payment_method_cod"]').text('<?php echo $text2; ?>');
else
$('input[id^="payment_method_cod"]').text('<?php echo $text1; ?>');
// 2. Live event detection:When shipping method is changed
$( 'form.checkout' ).on( 'change', 'input[name^="shipping_method[0]"]', function() {
var choosenDeliveryMethod = $('input[name^="shipping_method[0]"]:checked').val(); // Chosen
if( choosenDeliveryMethod == 'samedaycourier:15:LN' )
$('input[id^="payment_method_cod"]').text('<?php echo $text2; ?>');
else
$('input[id^="payment_method_cod"]').text('<?php echo $text1; ?>');
});
});
</script>
<?php
}
CodePudding user response:
No need to use jQuery, you can use the woocommerce_gateway_title
filter hook and WC()->session->get( 'chosen_shipping_methods' )
Adjust $payment_id === ''
and the result of $chosen_shipping_methods
to your needs
So you get:
function filter_woocommerce_gateway_title( $title, $payment_id ) {
// Only on checkout page and for COD
if ( is_checkout() && ! is_wc_endpoint_url() && $payment_id === 'cod' ) {
// Get chosen shipping methods
$chosen_shipping_methods = (array) WC()->session->get( 'chosen_shipping_methods' );
// Compare
if ( in_array( 'local_pickup:1', $chosen_shipping_methods ) ) {
$title = __( 'My title', 'woocommerce' );
} elseif ( in_array( 'lsamedaycourier:7:24', $chosen_shipping_methods ) ) {
$title = __( 'Credit Card on Delivery', 'woocommerce' );
} else {
$title = __( 'Another title', 'woocommerce' );
}
}
return $title;
}
add_filter( 'woocommerce_gateway_title', 'filter_woocommerce_gateway_title', 10, 2 );
Note: to find the correct $chosen_shipping_methods
(ID), you can use (part 2) "For debugging purposes" from this answer