I am not a developer and I don’t know much about code so I’m struggling a bit with this.
I have a shop that ships mainly to Peru, but i want to offer shipping to other countries now. The problem I have is that there are more fields for shipping within Peru while for other countries those are not necessary so I would like to hide/remove those when any other country that isn’t Peru is selected.
I tried using the code below while setting a flat rate (flat_rate:3) for all other countries. The following three fields would hide ‘billing_id’, ‘billing_address_2’ , ‘billing_reference’. When changing countries automatically the shipping option would change to flat rate and the fields would hide, it was working yesterday but today it only works if i change the country and then refresh the site. I’m not sure if i’m doing something wrong, or if there’s any other way I could do it. I am using Code Snippets to add the code.
/* This piece of code will hide fields for the chosen method.
.hide_pickup {
display: none !important;
}
*/
// Hide Local Pickup shipping method
add_filter( 'woocommerce_checkout_fields', 'hide_local_pickup_method' );
function hide_local_pickup_method( $fields_pickup ) {
// change below for the method
$shipping_method_pickup ='flat_rate:3';
// change below for the list of fields. Add (or delete) the field name you want (or don’t want) to use
$hide_fields_pickup = array( 'billing_id', 'billing_address_2' , 'billing_reference' );
$chosen_methods_pickup = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping_pickup = $chosen_methods_pickup[0];
foreach($hide_fields_pickup as $field_pickup ) {
if ($chosen_shipping_pickup == $shipping_method_pickup) {
$fields_pickup['billing'][$field_pickup]['required'] = false;
$fields_pickup['billing'][$field_pickup]['class'][] = 'hide_pickup';
}
$fields_pickup['billing'][$field_pickup]['class'][] = 'billing-dynamic_pickup';
}
return $fields_pickup;
}
// Local Pickup - hide fields
add_action( 'wp_head', 'local_pickup_fields', 999 );
function local_pickup_fields() {
if (is_checkout()) :
?>
<style>
.hide_pickup {display: none!important;}
</style>
<script>
jQuery( function( $ ) {
if ( typeof woocommerce_params === 'undefined' ) {
return false;
}
$(document).on( 'change', '#shipping_method input[type="radio"]', function() {
// change flat_rate:3 accordingly
$('.billing-dynamic_pickup').toggleClass('hide_pickup', this.value == 'flat_rate:3');
});
});
</script>
<?php
endif;
}
2
Answers
Thanks to Bhautik who told me to use updated_checkout, I am leaving here the code i am using and that works correctly for me!
You can use the
updated_checkout
trigger that is called after the checkout update. try the below code.