问题
how can I make "Ship to a different address" checked when Free shipping or Flat rate is selected and Unchecked if Local pickup is selected.
All I can see is either all 3 shipping methods are checked by default or not.
Any advice would be much appreciated.
Give thanks
回答1:
Here is the way to show / hide checkout shipping fields (auto checking / unchecking "ship to different address" checkbox, based on the chosen shipping method. It will automatically show the shipping fields when the chosen shipping method is "Flat rate" or "Free Shipping" and will hide the shipping fields for the others chosen shipping methods:
// Auto Show hide checkout shipping fields based on chosen shipping methods
add_action( 'wp_footer', 'custom_checkout_field_script' );
function custom_checkout_field_script() {
// Only on checkout page
if( is_checkout() && ! is_wc_endpoint_url() ):
// Get shipping methods rates data
$rates = WC()->session->get('shipping_for_package_0')['rates'];
$sdata = []; // Initializing an empty array
// Loop through shipping methods
foreach( $rates as $rate ){
// Targeting only "Flat rate" and "free shipping" shipping methods
if ( in_array( $rate->method_id, ['flat_rate', 'free_shipping'] ) ) {
// Add those shipping methods rate Ids in the array
$sdata[] = $rate->id;
}
}
// Jquery code start
?>
<script>
jQuery(function($){
var a = 'input[name^="shipping_method"]', b = a+':checked',
c = 'input#ship-to-different-address-checkbox',
d = <?php echo json_encode( $sdata ); ?>;
// Conditional function that checks if the chosen shipping method enables "shipping fields"
function rateIdEnableCheckbox( rateID, d ) {
var e = false;
// Loop through all available shipping methods Ids
$.each( d, function( k, v ){
if( rateID == v ){
e = true;
}
});
return e;
}
// function that show or hide shipping address fields (checkbox)
function showHideShippingAddressFields( b, c, d ) {
var f = $(c).prop("checked") ? true : false,
g = rateIdEnableCheckbox( $(b).val(), d );
if ( ( g && ! f ) || ( ! g && f ) ) {
$(c).click(); // Clik the checkbox (show hide shipping address)
}
// console.log($(b).val());
}
// 1. On load, the chosen shipping method
setTimeout(function(){
showHideShippingAddressFields( b, c, d );
}, 100);
// 2. On change shipping method (Live event)
$( 'form.checkout' ).on( 'change', a, function() {
showHideShippingAddressFields( b, c, d );
});
});
</script>
<?php
endif;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
来源:https://stackoverflow.com/questions/61650202/how-to-make-ship-to-different-address-checked-when-using-free-shipping-and-flat