Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This code allows you to make some WooCommerce Checkout Fields optional.
<?php
/*
This code allows you to make some WooCommerce Checkout Fields optional.
Blog post http://orbisius.com/link/3710
Author: Svetoslav Marinov (Slavi)
Author URI: http://orbisius.com
*/
/*
Installation
1. Paste the code below in your functions.php OR create an mu-plugin in wp-content/mu-plugins/orbisius_quick_fix_wc_ext_opt_co_fields.php
2. Define which fields you want optional by putting this in your wp-config.php
You can see the fields on the blog post about this fix at http://orbisius.com/link/3710
define('ORBISIUS_QUICK_FIX_WOO_OPTIONAL_CHECKOUT_FIELDS', 'first_name,last_name' );
3. If you want a customizaiton ($) contact me.
*/
add_filter( 'woocommerce_checkout_fields', 'orbisius_quick_fix_wc_ext_opt_co_fields_make_optional_fields', 25);
add_filter( 'woocommerce_billing_fields', 'orbisius_quick_fix_wc_ext_opt_co_fields_make_optional_fields', 25);
add_filter( 'woocommerce_default_address_fields', 'orbisius_quick_fix_wc_ext_opt_co_fields_make_optional_fields', 25);
/**
* This function does the heavy lifting to make fields optional.
* @param array $fields
* @return array
* @copyright (c) 2017 Slavi Marinov, http://orbisius.com
*/
function orbisius_quick_fix_wc_ext_opt_co_fields_make_optional_fields($fields) {
static $optional_fields = null;
// Don't know what to process so let's get out of here.
if (!defined('ORBISIUS_QUICK_FIX_WOO_OPTIONAL_CHECKOUT_FIELDS')) {
return $fields;
}
if (is_null($optional_fields)) {
$optional_fields = preg_split('#\s*[\,\;\|\r\n]+\s*#si', ORBISIUS_QUICK_FIX_WOO_OPTIONAL_CHECKOUT_FIELDS );
$optional_fields = array_unique($optional_fields);
$optional_fields = array_filter($optional_fields);
}
// Nothing to process so let's get out of here.
if (empty($optional_fields)) {
return $fields;
}
foreach ($optional_fields as $field_key) {
if (isset($fields[$field_key])) {
$fields[$field_key]['required'] = false;
}
if (isset($fields['shipping'][$field_key])) {
$fields[$field_key]['shipping']['required'] = false;
}
if (isset($fields['billing'][$field_key])) {
$fields[$field_key]['billing']['required'] = false;
}
// do we have fields that don't have a prefix?
$no_prefix_key = $field_key;
$no_prefix_key = preg_replace( '#(billing|shipping)_#si', '', $no_prefix_key);
if (isset($fields[$no_prefix_key])) {
$fields[$no_prefix_key]['required'] = false;
}
if (isset($fields['shipping'][$no_prefix_key])) {
$fields[$no_prefix_key]['shipping']['required'] = false;
}
if (isset($fields['billing'][$no_prefix_key])) {
$fields[$no_prefix_key]['billing']['required'] = false;
}
}
return $fields;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.