Woocommerce

Add loading animation in add to cart button in Woocommerce

The code, adds a loading animation when the add to cart button is clicked. then ckecks if the button has been added to cart, if not, it means that something came up. for example this can help when you have required product options and they are left empty. In the end of the code, we also change the Add to cart text to Next.

    
add_action( 'wp_footer', 'single_add_to_cart_event_text_replacement' ); function single_add_to_cart_event_text_replacement() { global $product; if ( ! is_product() ) { return; // Only single product pages } if ( $product->is_type('variable') ) { return; // Not variable products } if ( $product->is_type('external') ) { return; // Not affiliate products } ?> <style> .single_add_to_cart_button.loading { position: relative; } .single_add_to_cart_button.loading:before { content: ''; display: inline-block; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 20px; height: 20px; background: url('<?php echo esc_url( admin_url( 'images/wpspin.gif' ) ); ?>') no-repeat center center; } </style> <script type="text/javascript"> (function($){ $(document).on('click', 'button.single_add_to_cart_button', function(){ var button = $(this); var originalText = button.html(); // Store the original button HTML // Add loading class to the button button.addClass('loading'); // Delay before checking cart status setTimeout(function() { // AJAX request to check if the product has been added to the cart $.ajax({ url: '<?php echo esc_url( wc_get_cart_url() ); ?>', method: 'GET', success: function(response) { if ( response.indexOf('<?php echo esc_js( $product->get_id() ); ?>') !== -1 ) { // Product has been added to the cart button.html('<?php _e( "Added to Cart", "woocommerce" ); ?>'); } else { // Product not added to the cart button.html(originalText); } }, error: function() { // Error occurred, revert back to original HTML button.html(originalText); }, complete: function() { // Remove loading class from the button button.removeClass('loading'); } }); }, 1000); // Adjust the delay time (in milliseconds) as needed }); })(jQuery); </script> <?php } //change button text function change_add_to_cart_text($text) { $text = 'Next'; // Set the new button text here return $text; } add_filter('woocommerce_product_single_add_to_cart_text', 'change_add_to_cart_text');

Leave a Reply

Your email address will not be published. Required fields are marked *