问题
In Woocommerce checkout page, I am trying to hide some payment gateways, keeping only "Cash on delivery" payment method (COD) when "Ship to a different address?" is checked.
I have tried Conditionally hiding et showing payment gateways with some changes, but I didn't worked. I have tried also different answer codes without succes.
How to keep only COD payment when "Ship to a different address?" is checked?
Any help is appreciated.
回答1:
The following code will hide all payment gateways except "Cash on delivery" (COD) when "Ship to a different address?" is checked (and the shipping checkout fields are shown):
// The jQuery Ajax request
add_action( 'wp_footer', 'checkout_billing_area_script' );
function checkout_billing_area_script() {
// Only checkout page
if( is_checkout() && ! is_wc_endpoint_url() ):
// Remove "ship_different" custom WC session on load
if( WC()->session->get('ship_different') ){
WC()->session->__unset('ship_different');
}
// jQuery Ajax code below
?>
<script type="text/javascript">
jQuery( function($){
if (typeof wc_checkout_params === 'undefined')
return false;
var a = '#ship-to-different-address-checkbox', b = '';
// Ajax function
function triggerSTDA( value ){
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'ship_different_address',
'ship_different': value,
},
success: function (result) {
$('body').trigger('update_checkout');
console.log(result); // For testing (to be removed)
}
});
}
$(a).on( 'change', function(){
b = $(this).prop('checked') === true ? 'yes' : 'no';
triggerSTDA( b );
});
});
</script>
<?php
endif;
}
// The Wordpress Ajax PHP receiver
add_action( 'wp_ajax_ship_different_address', 'get_ajax_ship_different_address' );
add_action( 'wp_ajax_nopriv_ship_different_address', 'get_ajax_ship_different_address' );
function get_ajax_ship_different_address() {
if ( isset($_POST['ship_different']) ){
WC()->session->set('ship_different', esc_attr($_POST['ship_different']));
echo $_POST['ship_different'];
}
die();
}
// Show/hide payment gateways
add_filter( 'woocommerce_available_payment_gateways', 'conditionally_hide_payment_gateways', 100, 1 );
function conditionally_hide_payment_gateways( $available_gateways ) {
if( WC()->session->get('ship_different') == 'yes' ) {
foreach( $available_gateways as $gateways_id => $gateways ){
if( $gateways_id !== 'cod' ) {
unset($available_gateways[$gateways_id]);
}
}
}
return $available_gateways;
}
Code goes in function.php file of your active child theme (or active theme). Tested and work.
来源:https://stackoverflow.com/questions/53565775/show-hide-payment-gateways-based-on-checkout-fields-in-woocommerce