I am trying to implement a feature in WooCommerce. I have two shipping methods. The default is a Flat rate, and the other one is Local pickup.
When the local pickup shipping method is selected, I want to display a select dropdown below it. If the flat rate shipping method is selected again, the select dropdown should be hidden.
I have tried the following approach to achieve this functionality, but it hasn't worked: Regardless of whether I choose the local pickup shipping method or not, the select dropdown always displays
function add_custom_select_box($method, $index) {
if ($method->method_id == 'local_pickup') {
echo '<select name="local_pickup_store" id="local_pickup_store" onchange="updateSelectedStore()">
<option value="choose_store">choose store</option>
<option value="store1">store1</option>
<option value="store2">store2</option>
</select>';
echo '<div id="selected_store_info"></div>';
}
}
add_action('woocommerce_after_shipping_rate', 'add_custom_select_box', 10, 2);
function save_local_pickup_store($order) {
if (isset($_POST['local_pickup_store'])) {
$local_pickup_store = sanitize_text_field($_POST['local_pickup_store']);
$order->update_meta_data('_local_pickup_store', $local_pickup_store);
}
}
add_action('woocommerce_checkout_create_order', 'save_local_pickup_store');
function display_local_pickup_store($order) {
$local_pickup_store = $order->get_meta('_local_pickup_store');
if ($local_pickup_store) {
echo '<p><strong>store:</strong> ' . esc_html($local_pickup_store) . '</p>';
}
}
add_action('woocommerce_admin_order_data_after_billing_address', 'display_local_pickup_store');
add_action('wp_footer', 'custom_local_pickup_script');
function custom_local_pickup_script() {
?>
<script>
function updateSelectedStore() {
var selectedStore = document.getElementById('local_pickup_store').value;
var selectedStoreInfo = document.getElementById('selected_store_info');
if (selectedStore !== 'choose_store') {
selectedStoreInfo.innerHTML = '<p><strong>Selected Store:</strong> ' + selectedStore + '</p>';
} else {
selectedStoreInfo.innerHTML = '';
}
}
</script>
<?php
}
Using dynamic styling will allow you to show hide your select field… I have revised completely your code. It will work only in checkout page. I have added validation to that custom field too.
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.