Make Order notes field required only when it is not hidden in Woocommerce checkout - php

In Woocommerce checkout page, I have managed to show or hide "Order notes" field when "ship-to-different-address" checkbox is checked or unchecked, using "Show hide Order notes field based on a checkbox in Woocommerce checkout" answer code to one of my questions.
I would like "Order notes" field to be required only when it's visible.
How can I make this "Order notes" field required when it's visible (not hidden) and enable the validation for it?
Any help is welcome.

The following code will make "Order notes" field to be required only when it's not hidden and will enable in this case the field validation.
Note (mandatory): The "Order notes" field has to be optional (just as in default Woocommerce), without that the code will not work properly.
The complete code:
// Remove "(optional)" label on "Order notes" field
add_filter( 'woocommerce_form_field' , 'remove_order_comments_optional_fields_label', 10, 4 );
function remove_order_comments_optional_fields_label( $field, $key, $args, $value ) {
// Only on checkout page for Order notes field
if( 'order_comments' === $key && is_checkout() ) {
$optional = ' <span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
$field = str_replace( $optional, '', $field );
}
return $field;
}
// The jQuery script that show hide "Order notes" field
add_action( 'woocommerce_after_order_notes', 'custom_checkout_scripts_js_script', 10, 1 );
function custom_checkout_scripts_js_script( $checkout ) {
$required = esc_html__( 'required', 'woocommerce' );
?>
<script type="text/javascript">
(function($){
var required = '<abbr class="required" title="<?php echo $required; ?>">*</abbr>',
notesField = '#order_comments_field',
shipCheckbox = '#ship-to-different-address-checkbox';
function actionRequire( actionToDo='yes', selector='' ){
if ( actionToDo == 'yes' ) {
$(selector).addClass("validate-required");
$(selector+' label').append(required);
} else {
$(selector).removeClass("validate-required");
$(selector+' label > .required').remove();
}
$(selector).removeClass("woocommerce-validated");
$(selector).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
}
// On load and on form change
$('form.checkout').on( 'change', shipCheckbox, function(){
if( $(this).prop('checked') === true ) {
$(notesField).hide(); // Show
actionRequire( 'no' ,notesField );
} else {
$(notesField).show(); // Hide
actionRequire( 'yes' ,notesField );
}
});
})(jQuery);
</script>
<?php
}
// "Order notes" field validation
add_action('woocommerce_checkout_process', 'order_comments_field_validation');
function order_comments_field_validation() {
if ( isset($_POST['order_comments']) && empty($_POST['ship_to_different_address']) )
wc_add_notice( __( 'Please fill in "Order notes" required field.' ), 'error' );
}
Code goes on function.php file of your active child theme (or active theme). Tested and works.
Similar: Make Woocommerce checkout phone field optional based on shipping country
Related: Show hide Order notes field based on a checkbox in Woocommerce checkout

Related

WooCommerce custom create account checkbox on checkout

We just moved and merged the WooCommerce account password field on the checkout page from the "Account" group to the "Billing" field group. This works nicely. Also, we create a new checkbox field and add this to the billing section. Without that, the "Create an account" checkbox will still be at the default position. To do so, we created a new checkbox with jQuery.
Thanks to the following articles:
How to move the create account checkbox on Woocommerce checkout page
Reordering checkout fields in WooCommerce 3
With our current code, the moved password field is always visible. We want to have it the same way as WooCommerce default works. This means the password field should only be visible when the checkbox is active. WooCommerce by default has an excellent hide & Show CSS in place. However, I'm not able to use the identical CSS (or maybe script?!).
How can we connect the custom checkbox with the account password field?
// Move Account password field into billing section
function move_password_field($checkout_fields){
// Move Account Password into Billing
$checkout_fields['billing']['account_password'] = $checkout_fields['account']['account_password'];
// Remove Password from Billing
unset($checkout_fields['account']['account_password']);
return $checkout_fields;
}
add_filter('woocommerce_checkout_fields', 'move_password_field', 999);
// CSS rules
add_action( 'woocommerce_before_checkout_billing_form', 'move_checkout_create_an_account_css' );
function move_checkout_create_an_account_css() {
if( ! is_user_logged_in() ) :
?><style>
.woocommerce-account-fields label.woocommerce-form__label-for-checkbox {display: none !important;}
#account_cb_field {margin-top: 32px;}
#account_cb_field input {margin-right: 6px;}
</style>
<?php
endif;
}
// Add a checkbox to billing section
add_filter( 'woocommerce_checkout_fields', 'move_checkout_create_an_account_checkbox' );
function move_checkout_create_an_account_checkbox( $fields ) {
if( ! is_user_logged_in() ) {
// Make email field on half on left side
$fields['billing']['billing_email']['class'] = array('form-row-wide');
// Custom checkbox on half right side
$fields['billing']['account_cb'] = array(
'type' => 'checkbox',
'label' => __("Create an account?", "woocommerce"),
'class' => array('form-row-wide'),
);
}
return $fields;
}
// remove "(optional)" from the new checkbox
add_filter( 'woocommerce_form_field' , 'remove_checkout_optional_fields_label', 10, 4 );
function remove_checkout_optional_fields_label( $field, $key, $args, $value ) {
// Only on checkout page
if ( is_checkout() && ! is_wc_endpoint_url() && $key === 'account_cb' ) {
$optional = ' <span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
$field = str_replace( $optional, '', $field );
}
return $field;
}
// The jQuery code
add_action( 'wp_footer', 'move_checkout_create_an_account_js' );
function move_checkout_create_an_account_js() {
if ( ! is_user_logged_in() && is_checkout() && ! is_wc_endpoint_url() ) :
?><script>
(function($){
$('input[name=account_cb]').on( 'click', function() {
$('input[name=createaccount]').trigger('click');
});
})(jQuery);
</script>
<?php
endif;
}

Set a default custom billing state field value in Woocommerce Admin page

I want to add some custom billing states and then set a default state in the Admin panel. So far I have added the states as follows (code below; also not sure this is right):
add_filter( 'woocommerce_states', 'custom_woocommerce_states' );
function custom_woocommerce_states( $states ) {
$states['PE'] = array(
'PE1' => __('StateA', 'woocommerce')
'PE2' => __('StateB', 'woocommerce')
);
return $states;
}
How do I set the default value to be StateA in the Admin Panel?
First, there is a mistake in your current code.
In Admin WooCommerce order pages when adding (or editing) billing (or shipping) address(es), to set custom 'PE1' as default state when selected country is Peru (PE), use the following instead:
add_filter( 'woocommerce_states', 'custom_woocommerce_states_for_peru' );
function custom_woocommerce_states_for_peru( $states ) {
// For PERU
$states['PE'] = array(
'PE1' => __('StateA', 'woocommerce'),
'PE2' => __('StateB', 'woocommerce')
);
return $states;
}
// Admin orders: Set a default state for PERU country
add_action( 'admin_footer', 'custom_admin_shop_order_js' );
function custom_admin_shop_order_js() {
global $pagenow, $post_type;
if ( in_array( $pagenow, array('post-new.php', 'post.php') ) && 'shop_order' === $post_type ) :
?><script type='text/javascript'>
jQuery( function($) {
// Billing state
$(document.body).on( 'change', 'select#_billing_country,select#_shipping_country', function(){
var country = 'PE', // Set country
defaultState = 'PE1', // Set default state (for country)
parent = $(this).parent().parent(),
billingState = parent.find('select#_billing_state'),
shippingState = parent.find('select#_shipping_state');
if( country === $(this).val() ) {
if ( '' === billingState.val() ) {
billingState.val(defaultState).trigger("change");
} else if ( '' === shippingState.val() ) {
shippingState.val(defaultState).trigger("change");
}
}
});
});
</script><?php
endif;
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
You can add some new custom states for a country using this code:
add_filter( 'woocommerce_states', 'custom_woocommerce_states' );
function custom_woocommerce_states( $states ) {
$states['XX'] = array( // XX is Country Code
'XX1' => 'State 1',
'XX2' => 'State 2'
);
return $states;
}
Then you can change the country and state default value using this code:
add_filter( 'default_checkout_billing_country', 'change_default_checkout_country' );
add_filter( 'default_checkout_billing_state', 'change_default_checkout_state' );
function change_default_checkout_country() {
return 'XX'; // country code
}
function change_default_checkout_state() {
return 'XX'; // state code
}
If you are trying to make it dynamic and choose your default state from your admin panel, you can add a section and an option to your Woocommerce settings and get it using get_option('custom_id'). You can get help for creating a custom setting for Woocommerce here.

How to move the create account checkbox on Woocommerce checkout page

On my current checkout page I have the "create account" checkbox after the email field. What I am attempting to do is to move the create account checkbox inline and next to the email field. So I would have the email field on the left and the created account checkbox to the right.
I am able to move the create account checkbox but I just cannot figure out how to achieve the look I described. Any help would be appreciated. Thank you!
Checkout page here :
https://www.dailymutt.com/checkout/
This can be done adding a new similar checkbox field to billing form and hiding the real checkbox one with CSS. Then with the help of jQuery, you can trigger the hidden checkbox from the duplicated one.
Here is that code:
// CSS rules
add_action( 'woocommerce_before_checkout_billing_form', 'move_checkout_create_an_account_css' );
function move_checkout_create_an_account_css() {
if( ! is_user_logged_in() ) :
?><style>
.woocommerce-account-fields label.woocommerce-form__label-for-checkbox {display: none !important;}
#account_cb_field {margin-top: 32px;}
#account_cb_field input {margin-right: 6px;}
</style>
<?php
endif;
}
// Add a checkbox to billing section
add_filter( 'woocommerce_checkout_fields', 'move_checkout_create_an_account_checkbox' );
function move_checkout_create_an_account_checkbox( $fields ) {
if( ! is_user_logged_in() ) {
// Make email field on half on left side
$fields['billing']['billing_email']['class'] = array('form-row-first');
// Custom checkbox on half right side
$fields['billing']['account_cb'] = array(
'type' => 'checkbox',
'label' => __("Create an account?", "woocommerce"),
'class' => array('form-row-last'),
);
}
return $fields;
}
// remove "(optional)" from the new checkbox
add_filter( 'woocommerce_form_field' , 'remove_checkout_optional_fields_label', 10, 4 );
function remove_checkout_optional_fields_label( $field, $key, $args, $value ) {
// Only on checkout page
if ( is_checkout() && ! is_wc_endpoint_url() && $key === 'account_cb' ) {
$optional = ' <span class="optional">(' . esc_html__( 'optional', 'woocommerce' ) . ')</span>';
$field = str_replace( $optional, '', $field );
}
return $field;
}
// The jQuery code
add_action( 'wp_footer', 'move_checkout_create_an_account_js' );
function move_checkout_create_an_account_js() {
if ( ! is_user_logged_in() && is_checkout() && ! is_wc_endpoint_url() ) :
?><script>
(function($){
$('input[name=account_cb]').on( 'click', function() {
$('input[name=createaccount]').trigger('click');
});
})(jQuery);
</script>
<?php
endif;
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Show/Hide WooCommerce Shipping Rates Based on Radio Buttons

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.
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 and flat_rate:4 shipping methods will be hidden, so customer will only be able to choose flat_rate:1 or flat_rate:2 shipping methods.
If "Residential" radio button is selected then flat_rate:1 and flat_rate:2 shipping methods will be hidden, so customer will only be able to choose flat_rate:3 or flat_rate:4 shipping methods.
The code:
// Display a Custom radio buttons fields for shipping options
add_action( 'woocommerce_review_order_before_payment','checkout_customer_type_radio_buttons' );
function checkout_customer_type_radio_buttons() {
$field_id = 'customer_type';
echo '<div id="customer-type-radio">';
echo '<h3>' . __("Select Your Business Type", "woocommerce") . '</h3>';
// Get the selected radio button value (if selected)
$field_value = WC()->session->get( $field_id );
// Get customer selected value on last past order
if( empty($field_value) )
$field_value = WC()->checkout->get_value( $field_id );
// The default value fallback
if( empty($field_value) )
$field_value = 'Business';
woocommerce_form_field( $field_id, array(
'type' => 'radio',
'class' => array( $field_id ),
'required' => true,
'options' => array(
'Business' => __('Business', 'woocommerce'),
'Residential' => __('Residential', 'woocommerce'),
),
), $field_value );
echo '</div>';
}
// Conditionally show/hide shipping methods
add_filter( 'woocommerce_package_rates', 'shipping_package_rates_filter_callback', 100, 2 );
function shipping_package_rates_filter_callback( $rates, $package ) {
$customer_type = WC()->session->get( 'customer_type' ); // Get the customere type
if ( $customer_type === 'Business' ) {
if( isset( $rates['flat_rate:3'] ) )
unset( $rates['flat_rate:3'] );
if( isset( $rates['flat_rate:4'] ) )
unset( $rates['flat_rate:4'] );
}
elseif ( $customer_type === 'Residential' ) {
if( isset( $rates['flat_rate:1'] ) )
unset( $rates['flat_rate:1'] );
if( isset( $rates['flat_rate:2'] ) )
unset( $rates['flat_rate:2'] );
}
return $rates;
}
// function that gets the Ajax data
add_action( 'wp_ajax_get_customer_type', 'wc_get_customer_type' );
add_action( 'wp_ajax_nopriv_get_customer_type', 'wc_get_customer_type' );
function wc_get_customer_type() {
$field_id = 'customer_type';
if ( isset($_POST[$field_id]) && ! empty($_POST[$field_id]) ){
WC()->session->set($field_id, $_POST[$field_id] );
}
echo json_encode( WC()->session->get( $field_id ) );
die(); // (required)
}
// The Jquery Ajax script
add_action( 'wp_footer', 'custom_checkout_ajax_jquery_script' );
function custom_checkout_ajax_jquery_script() {
$field_id = 'customer_type';
if( WC()->session->__isset($field_id) )
WC()->session->__unset($field_id);
// Only on checkout when billing company is not defined
if( is_checkout() && ! is_wc_endpoint_url() ):
?>
<script type="text/javascript">
jQuery( function($){
if (typeof wc_checkout_params === 'undefined')
return false;
var fieldId = 'p#customer_type_field input';
function userTypeTriggerAjax( customerType ){
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'get_customer_type',
'customer_type': customerType,
},
success: function (result) {
// Trigger refresh checkout
$('body').trigger('update_checkout');
console.log(result);
}
});
}
// On start
if( $(fieldId).val() != '' ) {
userTypeTriggerAjax( $(fieldId).val() );
}
// On change
$(fieldId).change( function () {
userTypeTriggerAjax( $(this).val() );
});
});
</script>
<?php
endif;
}
// Enabling, disabling and refreshing session shipping methods data
add_action( 'woocommerce_checkout_update_order_review', 'refresh_shipping_methods', 10, 1 );
function refresh_shipping_methods( $post_data ){
$bool = true;
if ( in_array( WC()->session->get('customer_type' ), ['Business', 'Residential'] ) )
$bool = false;
// Mandatory to make it work with shipping methods
foreach ( WC()->cart->get_shipping_packages() as $package_key => $package ){
WC()->session->set( 'shipping_for_package_' . $package_key, $bool );
}
WC()->cart->calculate_shipping();
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Code based on this related threads:
Remove shipping cost if custom checkbox is checked in WooCommerce Checkout
Show/hide shipping methods based on a WooCommerce checkout field value
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:
//if( empty($field_value) )
$field_value = '';
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:
// Show notice if customer does not select a business type
add_action( 'woocommerce_checkout_process', 'business_type_error_message' );
function business_type_error_message() {
if ( ! (int) isset( $_POST['customer_type'] ) ) {
wc_add_notice( __( 'Please select an order type to calculate the correct shipping and proceed with your order.' ), 'error' );
}
}
Hope this helps others out there!

Woocommerce: Making a billing field optional for a specific country does not work

In my Wordpress Woocommerce site I need to skip the required validation for billing city field when the user selects a specific billing country.
I have referred answers in the following similar questions but both these don't seem to work on my checkout page. All I did was copy pasting those functions in the functions.php of the active theme and changed the fields and function names accordingly. But the changes or the codes don't appear in the source code of the checkout page and the required validation still works for the countries where the city is not required to be entered.
Referred (Neither of the following answers work for my checkout page)
Make checkout phone field optional for specific countries in WooCommerce
Make Woocommerce checkout phone field optional based on shipping country
My Code
// Making the billing city field not required (by default)
add_filter( 'woocommerce_billing_fields', 'filter_billing_city_field');
function filter_billing_city_field( $fields ) {
$fields['billing_city']['required'] = false;
return $fields;
}
// Real time country selection actions
add_action( 'woocommerce_after_order_notes', 'custom_checkout_scripts_and_fields', 8, 1 );
function custom_checkout_scripts_and_fields( $checkout ) {
$required = esc_attr__( 'required', 'woocommerce' );
// HERE set the countries codes (2 capital letters) in this array:
$countries = array( 'LK');
// Hidden field for the phone number validation
echo '<input type="hidden" name="billing_city_check" id="billing_city_check" value="0">';
$countries_str = "'".implode( "', '", $countries )."'"; // Formatting countries for jQuery
?>
<script type="text/javascript">
(function($){
var required = '<abbr class="required" title="<?php echo $required; ?>">*</abbr>',
countries = [<?php echo $countries_str; ?>],
location = $('#billing_country option:selected').val(),
cityCheck = 'input#billing_city_check';
function actionRequire( actionToDo='yes', selector='' ){
if ( actionToDo == 'yes' ) {
$(selector).addClass("validate-required");
$(selector+' label').append(required);
} else {
$(selector).removeClass("validate-required");
$(selector+' label > .required').remove();
}
$(selector).removeClass("woocommerce-validated");
$(selector).removeClass("woocommerce-invalid woocommerce-invalid-required-field");
}
// Default value when loading
actionRequire( 'no','#billing_city_check' );
if( $.inArray( location, countries ) >= 0 && $(cityCheck).val() == '0' ){
actionRequire( 'yes','#billing_city_check' );
$(cityCheck).val('1');
}
// Live value
$( 'form.checkout' ).on( 'change', '#billing_country', function(){
var location = $('#billing_country option:selected').val();
if ( $.inArray( location, countries ) >= 0 && $(cityCheck).val() == 0 ) {
actionRequire( 'yes','#billing_city_check' );
$(cityCheck).val('1');
} else if ( $(cityCheck).val() == 1 ) {
actionRequire( 'no','#billing_city_check' );
$(cityCheck).val('0');
}
});
})(jQuery);
</script>
<?php
}
// City validation, when it's visible
add_action('woocommerce_checkout_process', 'billing_city_field_process');
function billing_city_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['billing_city'] && $_POST['billing_city_check'] == '1' )
wc_add_notice( __( 'Please enter city.' ), 'error' );
}
Add this code snippet in your activated theme function.php at the end.
add_filter('woocommerce_billing_fields', 'vg_customize_checkout_form');
function vg_customize_checkout_form($fields)
{
$fields['billing_city']['required'] = false;
return $fields;
}
#Source: https://github.com/woocommerce/woocommerce/blob/master/includes/class-wc-checkout.php#L845
add_action('woocommerce_after_checkout_validation', 'vg_custom_validation_billing_city', 10, 2);
function vg_custom_validation_billing_city($fields, $error)
{
if('IN' != $fields['billing_country'] && empty($fields['billing_city'])) {
$error->add('validation', 'City is required field.');
}
}
Let's see each hook functionality:
Filter Hook: woocommerce_billing_fields
Official Document:
https://docs.woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/#section-8
https://docs.woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/#section-2
Purpose: We can alter the predefined properties of the field by overriding the array element as we have overridden the required property of the billing_city field
Action Hook: woocommerce_after_checkout_validation
Official Document:
https://docs.woocommerce.com/wc-apidocs/source-class-WC_Checkout.html#830
Purpose: To add custom code after the cart has been successfully checkout. Here we can add our custom validation and based on validation success or failure we can through error.
Here we verified whether the billing country is not India then the city should be filled. If the user not filled the city for other than India then our custom error City is a required field. will be thrown.
Reference:
https://docs.woocommerce.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/
https://docs.woocommerce.com/wc-apidocs/hook-docs.html

Categories