如果选择送货选项,我正在尝试切换(COD)货到付款标签
用户有两种交付方式:
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_samedaycourier724" value="samedaycourier:7:24" class="shipping_method">
<input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_samedaycourier15ln" value="samedaycourier:15:LN" class="shipping_method" checked="checked">
如果选中了值="samedaycourier:15:LN">我希望货到付款标签是信用卡货到付款而不是货到付款
我复制了一个类似的代码,并试图使其适应我的需要,不幸的是没有预期的结果。任何建议吗?
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
}
无需使用jQuery,可以使用woocommerce_gateway_title
过滤器钩子和WC()->session->get( 'chosen_shipping_methods' )
根据需要调整$payment_id === ''
和$chosen_shipping_methods
的结果
得到:
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 );
注意:要找到正确的$chosen_shipping_methods
(ID),您可以使用(第2部分)"用于调试目的"。从这个答案
这是我在EasyBox服务中使用的代码(是来自blobloom的修改代码):
add_filter( 'woocommerce_available_payment_gateways', 'bbloomer_gateway_disable_for_shipping_rate' );
function bbloomer_gateway_disable_for_shipping_rate( $available_gateways ) {
if ( ! is_admin() ) {
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$method_key_id = $chosen_methods[0];
if ( isset( $available_gateways['cod'] ) && 0 === strpos( $method_key_id, 'samedaycourier:15:LN' ) ) {
unset( $available_gateways['cod'] );
}
}
return $available_gateways;
}