I’ve been looking for a solution to this for a while now… I am trying to show or hide specific shipping rates based on a radio button option added to the Woocommerce checkout page. But I don’t know anything about Ajax & JQuery which I believe it requires.
Basically if a user selects radio option_1 it will ONLY show ‘flat_rate:1‘ & ‘flat_rate:2‘. If the user selects radio option_2 it will ONLY show ‘flat_rate:3‘ & ‘flat_rate:4‘
Click here for example of checkout screen
Here is the code for my radio buttons displayed on checkout page:
add_action( 'woocommerce_review_order_before_payment','tc_checkout_radio_choice' );
function tc_checkout_radio_choice() {
$businesstype = array(
'type' => 'radio',
'class' => array( 'business_residential' ),
'required' => true,
'options' => array(
'option_1' => 'Business',
'option_2' => 'Residential',
),
);
echo '<div id="checkout-radio">';
echo '<h3>Select Your Business Type</h3>';
woocommerce_form_field( 'radio_choice', $businesstype );
echo '</div>';
}
The closest example I’ve seen comes from an answer provided by ‘LoicTheAztec‘ in this post here: Show/hide shipping methods based on a WooCommerce checkout field value
I’m completely lost with this and the more I try to solve it, the more I get confused.
2
Answers
If anyone wants to know how to make this a required option with an error notification before payment, this is what I did...
To de-select the radio buttons I removed the value from:
And added this code to the checkout process at the end of the code from Loic, which adds a notification message if a radio button has not been selected:
Hope this helps others out there!
Here is the correct way to show hide shipping methods based on multiple radio buttons choice on checkout page, that requires to use PHP, Ajax, jQuery and WC Session.
When “Business” radio button is selected (default choice),
flat_rate:3
andflat_rate:4
shipping methods will be hidden, so customer will only be able to chooseflat_rate:1
orflat_rate:2
shipping methods.If “Residential” radio button is selected then
flat_rate:1
andflat_rate:2
shipping methods will be hidden, so customer will only be able to chooseflat_rate:3
orflat_rate:4
shipping methods.The code:
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Code based on this related threads: