Trying to prevent WooCommerce to submit the checkout form in order to manipulate the data submitted, I found that the plugin uses the jQuery “triggerHandler” function. That’s cool because you can use it to check for your custom data for example.
The actual use
Say you want to validate the form using WooCommerce’s Ajax calls, but prevent the actual order submission so you can add extra steps ( like presenting some up-sell offers ). In this case you can hook with js in a manner similar to the one below:
var checkout_form = $( 'form.checkout' ); checkout_form.on( 'checkout_place_order', function() { // do your custom stuff checkout_form.append('<input type="hidden" name="m_prevent_submit" value="1">'); // return true to continue the submission or false to prevent it return true; });
What you can do next is: allow the validation to go through just before the order is added and trigger a custom notice.
You’ll need to hook into “woocommerce_after_checkout_validation” and check if the hidden input we added previously is present. If it is and no error was previously recorded you can trigger the error.
add_action('woocommerce_after_checkout_validation', 'm_prevent_submission'); function m_prevent_submission($posted) { if ( isset($_POST['m_prevent_submit']) && wc_notice_count( 'error' ) == 0 ) { wc_add_notice( __( "custom_notice", 'm_example' ), 'error'); // change the data in $posted here } }
Afterwards, in Javascript you can check for your custom error using a function like:
$( document.body ).on( 'checkout_error', function() { var error_text = $('.woocommerce-error').find('li').first().text(); if ( error_text=='custom_notice' ) { // do your custom js stuff } });
The same logic can be applied for example to changing the cart redirect for specific products, more on that on a future post.