Add to Cart Without a Page Reload on Product Pages
Adds simple products to the cart in the background from the product page, updating the mini cart and showing a confirmation instead of reloading the page.
Opens WPIDE on
Code
add_action( 'wp_footer', function () {
if ( ! function_exists( 'is_product' ) || ! is_product() ) {
return;
}
?>
<script>
( function () {
var form = document.querySelector( '.product-type-simple form.cart' );
if ( ! form || ! window.fetch ) { return; }
form.addEventListener( 'submit', function ( event ) {
var button = form.querySelector( '[name="add-to-cart"]' );
if ( ! button ) { return; }
event.preventDefault();
var data = new FormData( form );
data.set( 'product_id', button.value );
data.delete( 'add-to-cart' );
button.classList.add( 'loading' );
button.disabled = true;
fetch( <?php echo wp_json_encode( WC_AJAX::get_endpoint( 'add_to_cart' ) ); ?>, { method: 'POST', body: data, credentials: 'same-origin' } )
.then( function ( response ) { return response.json(); } )
.then( function ( result ) {
if ( ! result || result.error ) { form.submit(); return; }
if ( window.jQuery ) { jQuery( document.body ).trigger( 'added_to_cart', [ result.fragments, result.cart_hash, jQuery( button ) ] ); }
var note = form.querySelector( '.wpide-added' ) || form.appendChild( document.createElement( 'p' ) );
note.className = 'wpide-added';
note.setAttribute( 'role', 'status' );
note.innerHTML = <?php echo wp_json_encode( esc_html( 'Added to your cart.' ) . ' <a href="' . esc_url( wc_get_cart_url() ) . '">' . esc_html( 'View cart' ) . '</a>' ); ?>;
} )
.catch( function () { form.submit(); } )
.finally( function () { button.classList.remove( 'loading' ); button.disabled = false; } );
} );
} )();
</script>
<?php
} );
Notes
Applies to simple products only, and the mini cart refreshes when WooCommerce's cart fragments script is loaded.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.