I have a checkbox which if checked opens a drop down field (requirements). If you try and send the Woocommerce order it conditionally checks if the field has content, if it doesn't it returns an error.
This all works accept when the requirements field does have information input it still treats it as not having content and returns the error.
As this is the basic way that forms should work I don't understand why I'm getting such a result. Here's the code:
/**
* Add a message field to the WC checkout
*/
add_action( 'woocommerce_before_checkout_form', 'custom_checkout_field' );
function custom_checkout_field( $checkout ) {
echo '<div id="message"><h3>' . __( '<i class="fas fa-envelope"></i> Message' ) . '</h3><p style="margin: 0 0 8px;">Would you like to leave a message?</p>';
woocommerce_form_field( 'checkbox', array(
'type' => 'checkbox',
'class' => array( 'msg-checkbox' ),
'label' => __( 'Yes' ),
), $checkout->get_value( 'checkbox' ) );
woocommerce_form_field( 'requirements', array(
'type' => 'text',
'class' => array('msg'),
'label' => __('Please input your message.'),
'placeholder' => __(''),
), $checkout->get_value( 'requirements' ));
echo '</div>';
}
/**
* Process checkout with additional custom field
*/
add_action('woocommerce_checkout_process', 'custom_checkout_field_process');
function custom_checkout_field_process() {
// Check if set, if not add an error.
if(isset($_POST['checkbox']) && ( empty($_POST['requirements'])));
wc_add_notice( __( 'Please let us know what you would like to do' ), 'error' );
}
I hope that makes sense. basically it works to a point but the validation for the input field doesn't work when it has content.
Thanks.
Update: Code improvements and added a show/hide functionality with jQuery
The only problem comes from the hook that you are using for your custom checkout fields. It output those fields outside the checkout form, so the values are never submitted and then always empty.
Instead you will use woocommerce_checkout_before_customer_details action hook for your first hooked function that will output those fields inside the checkout form this time:
// Output custom checkout fields
add_action( 'woocommerce_checkout_before_customer_details', 'custom_checkout_field_before_billing' );
function custom_checkout_field_before_billing() {
$domain = 'woocommerce';
// Hide the message text field on load
?>
<style>p#requirements_field{display:none;}</style>
<div id="message">
<h3><i class="fa fa-envelope"></i><?php _e( 'Message', 'woocommerce' ); ?></h3>
<?php
woocommerce_form_field( 'checkbox_msg', array(
'type' => 'checkbox',
'class' => array( 'msg-checkbox' ),
'label' => __( 'Would you like to leave a message?', 'woocommerce' ),
), WC()->checkout->get_value( 'cb_msg' ));
woocommerce_form_field( 'requirements', array(
'type' => 'text',
'class' => array('msg t_msg'),
'label' => __('Please input your message.'),
'placeholder' => __(''),
), WC()->checkout->get_value( 'requirements' ));
echo '</div>';
// jQuery: show hide the text requirement field
?><script>
jQuery(document).ready(function($) {
var a = '#requirements_field';
$('input#checkbox_msg').change( function(){
if( $(this).is(':checked') )
$(a).show();
else
$(a).hide();
});
});
</script><?php
}
// Process checkout with additional custom field
add_action('woocommerce_after_checkout_validation', 'custom_checkout_field_validation_process', 20, 2 );
function custom_checkout_field_validation_process( $data, $errors ) {
// Check if set, if not add an error.
if( isset($_POST['checkbox_msg']) && empty($_POST['requirements']) )
$errors->add( 'requirements', __( "Please let us know what you would like to do filling up the message field.", "woocommerce" ) );
}
Code goes in function.php file of your active child theme (or active theme).
Tested and works.
Related
I write a code for add custom filed in checkout form as add affiliate code I want to match that custom field data with username. If custom field data match with any of the username the chcekout process move further other wise show error. I have write something but it's not working please help to solve this issue.
Here is my code:
// adding custom filed
add_action('woocommerce_before_checkout_form', 'custom_checkout_field');
function custom_checkout_field($checkout)
{
echo '<div id="custom_checkout_field"><h2>' . __('Add Reference Affiliate Code') . '</h2>';
woocommerce_form_field('custom_field_name', array(
'type' => 'text',
'class' => array(
'my-field-class form-row-wide'
) ,
'label' => __('Affiliate Code') ,
'placeholder' => __('Affiliate Code') ,
) ,
$checkout->get_value('custom_field_name'));
echo '</div>';
}
// Chcek custom filed data with username
add_action('woocommerce_checkout_process', 'custom_checkout_field_validation');
function custom_checkout_field_validation() {
if(username_exists( $_POST['custom_field_name'] )){
}else{
echo $_POST['custom_field_name'];
wc_add_notice( __( $_POST['custom_field_name']), 'error' );
wc_add_notice( __( 'Lütfen Geçerli TC Kimlik No Girin.' ), 'error' );
}
}
I am seeing a strange issue on my test website. The website can be viewed here and it's a test site so there's no payment (an no payment details entry is required).
https://puffpastrydelights.com/order-online/
So what I am trying to do is ensure the user has provided a delivery date or time if they choose delivery, or ensure they have provided a pickup date and time if they choose pickup.
So for replication, if you order a food item, in the shopping cart select pickup and then in the checkout page fill all the details, your checkout will process and everything is fine.
Now try the same again but this time select delivery in the cart page before you head to checkout, you will see it will show a validation error stating to provide delivery date and time even though you have. It's this I am unsure on and can't see in my code what's causing this issue:
// 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 ='local_pickup:2';
// 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_company', 'billing_state', 'billing_company');
$shipping_fields_pickup = array( 'shipping_first_name', 'shipping_last_name', 'shipping_company', 'shipping_address_1', 'shipping_address_2', 'shipping_city', 'shipping_postcode');
$hide_pickup_date_time = array( 'pickup_date', 'pickup_time');
$hide_delivery_date_time = array( 'delivery_date', 'delivery_time');
$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';
}
foreach($shipping_fields_pickup as $shipping_field ) {
if ($chosen_shipping_pickup == $shipping_method_pickup) {
$fields_pickup['shipping'][$shipping_field]['required'] = false;
}
}
foreach($hide_pickup_date_time as $pickup_date_time ) {
if ($chosen_shipping_pickup != $shipping_method_pickup) {
$fields_pickup['order'][$pickup_date_time]['required'] = false;
}
}
foreach($hide_delivery_date_time as $delivery_date_time ) {
if ($chosen_shipping_pickup != $shipping_method_pickup) {
$fields_pickup['order'][$delivery_date_time]['required'] = false;
}
}
return $fields_pickup;
}
/**
* Process the checkout
*/
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
$shipping_method_pickup ='local_pickup:2';
$chosen_methods_pickup = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping_pickup = $chosen_methods_pickup[0];
// Check if set, if its not set add an error.
if ($chosen_shipping_pickup == $shipping_method_pickup) {
if ( ! $_POST['pickup_date'] ){
wc_add_notice( __( 'Please provide a Pickup Date.' ), 'error' );
}
if ( ! $_POST['pickup_time'] ){
wc_add_notice( __( 'Please provide a Pickup Time.' ), 'error' );
}
} else {
if ( ! $_POST['delivery_date'] ){
wc_add_notice( __( 'Please provide a Delivery Date.' ), 'error' );
}
if ( ! $_POST['delivery_time'] ){
wc_add_notice( __( 'Please provide a Delivery Time.' ), 'error' );
}
}
}
These fields are custom fields and are set below like so:
add_action('woocommerce_before_order_notes', 'custom_checkout_field');
function custom_checkout_field($checkout)
{
echo '<div id="custom_checkout_field"><h3>' . __('Pickup/Delivery') . '</h3>';
woocommerce_form_field(
'delivery_date',
array(
'type' => 'date',
'required' => 'true',
'class' => array(
'delivery-date-class form-row-wide'
),
'label' => __('Delivery Date'),
),
$checkout->get_value('delivery_date')
);
woocommerce_form_field(
'delivery_time',
array(
'type' => 'time',
'required' => 'true',
'class' => array(
'delivery-time-class form-row-wide'
),
'label' => __('Delivery Time'),
),
$checkout->get_value('delivery_time')
);
woocommerce_form_field(
'pickup_date',
array(
'type' => 'date',
'required' => 'true',
'class' => array(
'pickup-date-class form-row-wide'
),
'label' => __('Pickup Date'),
),
$checkout->get_value('pickup_date')
);
woocommerce_form_field(
'pickup_time',
array(
'type' => 'time',
'required' => 'true',
'class' => array(
'pickup-time-class form-row-wide'
),
'label' => __('Pickup Time'),
),
$checkout->get_value('pickup_time')
);
echo '</div>';
}
Your code is correct, no errors.
The problem is that you have two HTML elements with the same id (and name) on the checkout page.
The fields are:
delivery_date there is a date input field and a text input field with this id (and name)
delivery_time there is a time input field and a text input field with this id (and name)
pickup_date there is a date input field and a text input field with this id (and name)
pickup_time there is a time input field and a text input field with this id (and name)
As you can see from this screenshot (the text input fields are hidden):
Try removing the text input fields or, if needed, change the id attribute value to be unique on the page.
In the code you published there is no reference to the text input fields, most likely they are in your functions.php.
I added custom email field on WooCommerce Checkout by following code
woocommerce_form_field('giftcard-friend-email', array(
'type' => 'email',
'class' => array( 'form-row-wide' ),
'required' => true,
'label' => __('To: Friend Email') ,
'placeholder' => __('Friend Email') ,
),
$checkout->get_value('giftcard-friend-email'));
It's working, required validation also working but it doesn't give error when input is an invalid email address.
I wonder if there's any built-in WooCommerce method to achieve this same as Billing Email?
Thanks!
You should always provide in your question the full function code and all related code too.
I have changed the giftcard-friend-email to _giftcard_friend_email a more normal slug as it will be saved as order meta data, so underscores are better option.
The following code will:
Display a custom email field in checkout page (so remove your code).
Will validate this email field checking that is not empty and a valid email.
Save this custom email value as order meta data when order is placed
The code:
// Display the custom checkout field
add_action('woocommerce_before_order_notes', 'add_custom_checkout_field', 20, 1 );
function add_custom_checkout_field( $checkout ) {
echo '<div id="friend_email_checkout_field">';
woocommerce_form_field( '_giftcard_friend_email', array(
'type' => 'email',
'label' => __('To: Friend Email') ,
'placeholder' => __('Friend Email') ,
'class' => array( 'form-row-wide' ),
'required' => true,
), $checkout->get_value('_friend_email') );
echo '</div>';
}
// Field custom email Validation
add_action( 'woocommerce_checkout_process', 'friend_email_checkout_field_validation' );
function friend_email_checkout_field_validation() {
if( isset($_POST['_giftcard_friend_email']) && empty($_POST['_giftcard_friend_email']) )
wc_add_notice( __( 'Please fill in the "Friend Email" field.', 'woocommerce' ), 'error' );
elseif( !preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $_POST['_giftcard_friend_email'] ) ){
wc_add_notice( __( 'Please enter a valid "Friend Email".', 'woocommerce' ), 'error' );
}
}
// Save the checkout field value to order meta data
add_action('woocommerce_checkout_create_order', 'save_friend_email_checkout_field_value', 20, 2 );
function save_friend_email_checkout_field_value( $order, $data ) {
if ( isset( $_POST['_giftcard_friend_email'] ) ) {
$order->update_meta_data( '_giftcard_friend_email', sanitize_email( $_POST['_giftcard_friend_email'] ) );
}
}
Code goes in function.php file of the active child theme (or active theme). Tested and works.
I have added two custom input fields in the shipping method section by changing the template /genesis-sample/woocommerce/checkout/review-order.php
I have also managed to get them conditionally required. Only when the specific radio button is checked, the input fields appear and become required. I am using jQuery code to make the fields appear and disappear. All of this is working fine. The code is here:
if ( isset($_POST['shipping_method_0_legacy_local_pickup']) && $_POST['shipping_method_0_legacy_local_pickup'] == 1 ) {
$cheq = 'true';
}
else {
$cheq = 'false';
}
woocommerce_form_field( 'fieldtester1' , array(
'type' => 'text',
'class' => array('wccs-field-class wccs-form-row-wide blahblah1'),
'label' => 'Enter Your Carrier Name',
'required' => $cheq,
'placeholder' => 'Carrier Name',
), $checkout->get_value( 'fieldtester1' ));
woocommerce_form_field( 'fieldtester2' , array(
'type' => 'text',
'class' => array('wccs-field-class wccs-form-row-wide blahblah2'),
'label' => 'Enter Your Carrier Account #',
'required' => $cheq,
'placeholder' => 'Carrier Number',
), $checkout->get_value( 'fieldtester2' ));
But here's the problem, even with the required attribute set as true for the two fields, the validation doesn't happen if the field is empty when the Place Order button is pressed. Ideally, the order should not go through and an error message should be generated. I have already added following code in functions.php to force validation of the input field but it doesn't do a thing. The code is here:
add_action('woocommerce_checkout_process', 'carrier_checkout_process');
function carrier_checkout_process() {
if ( isset($_POST['shipping_method_0_legacy_local_pickup']) && $_POST['shipping_method_0_legacy_local_pickup'] == 1 ) {
if( empty( $_POST['fieldtester1'] ) ) {
wc_add_notice( ( "Please don't forget to enter your shipping carrier details." ), "error" );
}
}
}
So, here's what I am looking for:
can anyone help me in forcing the validation for two input fields I
have added?
After the validation, I would also like to add these two fields in the new order email, and order details in the Wordpress dashboard.
If you are wondering why I am not using a woocommerce checkout field hook to add the input fields in the first place...I am not adding the fields to the checkout form so the hooks aren't of any help. The fields are added in the shipping method section. Another reason was, I wanted to update the required attribute every time a user would switch the shipping method. Using Jquery to change the required attribute wasn't working for whatever reason, believe me I tried for two days. Anyways, that part is already working. The only issues are getting the fields to validate and add them to the order emails and order details. I have looked around everywhere and the closest help I got was this post where LoicTheAztec gave a detailed solution
This can be done without jQuery using a special hook that will display your two "Carrier" custom fields below legacy_local_pickup shipping method when it's selected. If customer change to a different shipping method, those fields will be removed.
So you should need to remove your customized template and all related code before.
Now the validation works perfectly and when "Carrier" custom fields are filled, they are saved in order meta data.
// Add custom fields to a specific selected shipping method
add_action( 'woocommerce_after_shipping_rate', 'carrier_custom_fields', 20, 2 );
function carrier_custom_fields( $method, $index ) {
if( ! is_checkout()) return; // Only on checkout page
$customer_carrier_method = 'legacy_local_pickup';
if( $method->id != $customer_carrier_method ) return; // Only display for "local_pickup"
$chosen_method_id = WC()->session->chosen_shipping_methods[ $index ];
// If the chosen shipping method is 'legacy_local_pickup' we display
if($chosen_method_id == $customer_carrier_method ):
echo '<div class="custom-carrier">';
woocommerce_form_field( 'carrier_name' , array(
'type' => 'text',
'class' => array('form-row-wide carrier-name'),
'label' => 'Carrier Information:',
'required' => true,
'placeholder' => 'Carrier Name',
), WC()->checkout->get_value( 'carrier_name' ));
woocommerce_form_field( 'carrier_number' , array(
'type' => 'text',
'class' => array('form-row-wide carrier-number'),
'required' => true,
'placeholder' => 'Carrier Number',
), WC()->checkout->get_value( 'carrier_number' ));
echo '</div>';
endif;
}
// Check custom fields validation
add_action('woocommerce_checkout_process', 'carrier_checkout_process');
function carrier_checkout_process() {
if( isset( $_POST['carrier_name'] ) && empty( $_POST['carrier_name'] ) )
wc_add_notice( ( "Please don't forget to enter the shipping carrier name." ), "error" );
if( isset( $_POST['carrier_number'] ) && empty( $_POST['carrier_number'] ) )
wc_add_notice( ( "Please don't forget to enter the shipping carrier account number." ), "error" );
}
// Save custom fields to order meta data
add_action( 'woocommerce_checkout_update_order_meta', 'carrier_update_order_meta', 30, 1 );
function carrier_update_order_meta( $order_id ) {
if( isset( $_POST['carrier_name'] ))
update_post_meta( $order_id, '_carrier_name', sanitize_text_field( $_POST['carrier_name'] ) );
if( isset( $_POST['carrier_number'] ))
update_post_meta( $order_id, '_carrier_number', sanitize_text_field( $_POST['carrier_number'] ) );
}
This code goes on functions.php file of your active child theme (or theme). Tested and works.
Not displayed:
Displayed when "Local Pickup" is selected:
In WooCommerce, I can get a field hooked into my WooCommerce cart page & showing up OK using the following in my theme's (Storefront) functions PHP:
<?
// ADD Custom Fields to Checkout Page
/**
* Add the field to the checkout
**/
add_action('woocommerce_after_order_notes', 'my_custom_checkout_field');
function my_custom_checkout_field( $checkout ) {
date_default_timezone_set('America/Los_Angeles');
$mydateoptions = array('' => __('Select PickupDate', 'woocommerce' ));
echo '<div id="my_custom_checkout_field"><h3>'.__('Delivery Info').'</h3>';
woocommerce_form_field( 'order_pickup_date', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'id' => 'datepicker',
'required' => true,
'label' => __('Delivery Date'),
'placeholder' => __('Select Date'),
'options' => $mydateoptions
),$checkout->get_value( 'order_pickup_date' ));
echo '</div>';
}
/**
* Process the checkout
**/
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
global $woocommerce;
// Check if set, if its not set add an error.
if (!$_POST['order_pickup_date'])
wc_add_notice( '<strong>PickupDate</strong> ' . __( 'is a required field.', 'woocommerce' ), 'error' );
}
/**
* Update the order meta with field value
**/
add_action('woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta');
function my_custom_checkout_field_update_order_meta( $order_id ) {
if ($_POST['order_pickup_date']) update_post_meta( $order_id, 'PickupDate', esc_attr($_POST['order_pickup_date']));
}
?>
However, the datepicker widget is not initiated when you click into the field. I know the following code is required in the header for JQuery to work:
<script>
$( function() {
$( "#datepicker" ).datepicker(); } );
</script>
This did not work for me, so I thought to put this function into the checkout.js file in Storefront theme, but the added field didn't have calendar widget functionality.
There's a lot of .js in the them do I need to start a new one for includes?
First you will need to:
Enqueu main jquery-ui datepicker script
Change your custom script starting it with jQuery(function($){ instead of $(function(){ …
So to enable datepicker for your custom text field your code will be:
// Register main datepicker jQuery plugin script
add_action( 'wp_enqueue_scripts', 'enabling_date_picker' );
function enabling_date_picker() {
// Only on front-end and checkout page
if( is_admin() || ! is_checkout() ) return;
// Load the datepicker jQuery-ui plugin script
wp_enqueue_script( 'jquery-ui-datepicker' );
}
// Call datepicker functionality in your custom text field
add_action('woocommerce_after_order_notes', 'my_custom_checkout_field', 10, 1);
function my_custom_checkout_field( $checkout ) {
date_default_timezone_set('America/Los_Angeles');
$mydateoptions = array('' => __('Select PickupDate', 'woocommerce' ));
echo '<div id="my_custom_checkout_field">
<h3>'.__('Delivery Info').'</h3>';
// YOUR SCRIPT HERE BELOW
echo '
<script>
jQuery(function($){
$("#datepicker").datepicker();
});
</script>';
woocommerce_form_field( 'order_pickup_date', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'id' => 'datepicker',
'required' => true,
'label' => __('Delivery Date'),
'placeholder' => __('Select Date'),
'options' => $mydateoptions
),$checkout->get_value( 'order_pickup_date' ));
echo '</div>';
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and works. On storefront theme you will get that:
You may need to style it…
Just an update that this is no longer necessary. With Woocommerce you can simply change the style to 'date' and it deals with the rest for you - yahoo!