Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save xlplugins/3ee0f40ef82505a3102a0f2bf68c4f23 to your computer and use it in GitHub Desktop.

Select an option

Save xlplugins/3ee0f40ef82505a3102a0f2bf68c4f23 to your computer and use it in GitHub Desktop.
Hide billing address section when cart total is zero (free products)
<?php
/**
* Hide billing address section when cart total is zero (free products)
*/
$hide_billing_init = function() {
static $done = false;
if ( $done ) return;
$done = true;
// Check if cart needs payment
$needs_payment = WC()->cart && ! WC()->cart->is_empty() && WC()->cart->needs_payment();
// Remove billing field validation when no payment needed
if ( ! $needs_payment ) {
add_filter( 'wfacp_checkout_fields', function( $fields ) {
if ( isset( $fields['billing'] ) ) {
foreach ( $fields['billing'] as $key => &$field ) {
unset( $field['required'], $field['validate'] );
}
}
return $fields;
}, 99999 );
}
// Add CSS/JS in footer
add_action( 'wp_footer', function() use ( $needs_payment ) {
?>
<script>
(function($) {
function toggleBilling(needsPayment) {
var $section = $('.wfacp_divider_billing').parents('.wfacp-section');
if ($section.length) {
$section.toggle(needsPayment);
}
}
// Initial state from PHP
toggleBilling(<?php echo $needs_payment ? 'true' : 'false'; ?>);
// Update on AJAX (coupon applied, etc.)
if (typeof wfacp_frontend !== 'undefined' && wfacp_frontend.hooks) {
wfacp_frontend.hooks.addAction('wfacp_ajax_response', function(fragments, data) {
if (data && typeof data.needs_payment !== 'undefined') {
toggleBilling(data.needs_payment);
}
});
}
})(jQuery);
</script>
<?php
}, 999 );
};
add_action( 'wfacp_before_process_checkout_template_loader', $hide_billing_init );
add_action( 'wfacp_after_checkout_page_found', $hide_billing_init );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment