Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JudeRosario/b4eee4e6d4d5686e2ba6 to your computer and use it in GitHub Desktop.
Save JudeRosario/b4eee4e6d4d5686e2ba6 to your computer and use it in GitHub Desktop.
Simplify WooCommerce checkout fields for free checkouts
<?php
function sv_free_checkout_fields() {
global $woocommerce ;
// Bail we're not at checkout, or if we're at checkout but payment is needed
if ( ! is_checkout() || ( is_checkout() && WC()->cart->needs_payment() ) ) {
return;
}
if ( $woocommerce->cart->total != 0 ) {
return;
}
if ( WC_Subscriptions_Cart::cart_contains_subscription() ) {
return;
}
// remove coupon forms since why would you want a coupon for a free cart??
remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10 );
// Remove the "Additional Info" order notes
add_filter( 'woocommerce_enable_order_notes_field', '__return_false' );
// Unset the fields we don't want in a free checkout
function unset_unwanted_checkout_fields( $fields ) {
// add or remove billing fields you do not want
// list of fields: http://docs.woothemes.com/document/tutorial-customising-checkout-fields-using-actions-and-filters/#section-2
$billing_keys = array(
'billing_company',
'billing_phone',
'billing_address_1',
'billing_address_2',
'billing_city',
'billing_postcode',
'billing_country',
'billing_state',
);
// unset each of those unwanted fields
foreach( $billing_keys as $key ) {
unset( $fields['billing'][$key] );
}
return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'unset_unwanted_checkout_fields' );
// A tiny CSS tweak for the account fields; this is optional
function print_custom_css() {
echo '<style>.create-account { margin-top: 6em; }</style>';
}
add_action( 'wp_head', 'print_custom_css' );
}
add_action( 'wp', 'sv_free_checkout_fields' );
@bkozlowski
Copy link

bkozlowski commented Nov 7, 2017

@JudeRosario - There appears to be a bug with the latest version of WooCommerce 3.x. Even though billing fields are unset upon checkout WooCommerce still has the fields set to "require" somehow. When a customer completes checkout it shows an error that the unset fields are required.

@lxc047
Copy link

lxc047 commented May 6, 2018

This code dosen't works for me. It displays the errors.

@jboulhous
Copy link

Hello, i also encountered the validation errors. In my case, the checkout was done by an ajax call, so the unset_unwanted_checkout_fields was never added to the filter woocommerce_checkout_fields. I already needed to adapt the line if ( ! is_checkout() || ( is_checkout() && WC()->cart->needs_payment() ) ) for my use case, and finally i did it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment