Make a custom field required on checkout
-
I have a basic wordpress install on latest version of woocommerce.
My goal is to throw an error if my custom field is empty. This field is in a different location than normal fields, it is in the shipping section of the checkout.
I have code in my functions.php that displays a “pickup_location” field on the checkout page.
This is what it what it looks like on the front end: https://www.dropbox.com/s/9bpcwnwg20xgayf/shipping.jpg?dl=0
Currently the user can checkout with my custom field empty. I’d like to show an error instead.
// add shipping fields if user selects local pickup on checkout add_action('woocommerce_after_shipping_rate', function( $method ) { if($method->label == 'Local pickup') { if ( isset($_POST['shipping_method']) && $_POST['shipping_method'][0] === 'local_pickup:2' ){ ?> <style> .shipping_location_box { margin: 15px 15px 10px 15px; } .shipping_location_box p { margin: 0 0 10px 20px; } </style> <div class="shipping_location_box"> <p>Choose your prefered pickup location</p> <select name="pickup_location" required> <option value="none">-- Select Location</option> <?php $my_wp_query = new WP_Query(); $all_wp_pages = $my_wp_query->query(array('post_type' => 'page', 'posts_per_page' => '-1')); $page_children = get_page_children(6, $all_wp_pages); foreach($page_children as $location): ?> <option value="<?php echo $location->post_title; ?>"><?php echo $location->post_title; ?></option> <?php endforeach; ?> </select> </div> <?php } // if post } // if local pickup });
Now I have a function that actually saves this field I created in the database. But I want to make this field required.
add_action('woocommerce_checkout_update_order_meta', function( $orderid, $data ) { if ( isset( $_POST['pickup_location'] ) && $_POST['pickup_location'] != 'none') { update_post_meta($orderid, 'pickup_location', htmlspecialchars($_POST['pickup_location'])); }else{ // need help here showing the error on checkout // this order still goes through when this field is empty // on the thank you page, this notice runs // id like this checkout process to throw and error and display this notice on the checkout page wc_add_notice( __( 'Please select a pickup location.' ), 'error' ); // exit(); } }, 10, 2);
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
- The topic ‘Make a custom field required on checkout’ is closed to new replies.