WooCommerce has a built-in AJAX functionality for adding products to the cart on archive pages (Shop page, product category pages, tag pages, etc.). Once you add a product, WooCommerce displays a “View Cart” button beside the “Add to Cart” one.
The “View Cart” button is a way to improve user experience, so that customers can quickly access their cart after adding a product. However, I’ve noticed on some client websites that this can mess up the product grid layout, confuse users and – sometimes – hurt the overall UX instead of improving it!
With the snippet below you’ll learn how to remove this button – surely you’re familiar with the CSS display:none method, so we will see a different approach here, so that the button doesn’t even load. Enjoy!
PHP+JS Snippet: Remove “View Cart” Button When Product is Added to Cart Via Ajax @ Shop, Cat, Archive Pages
This code snippet aims to remove the “View Cart” button that typically appears after an AJAX add to cart event in WooCommerce.
Code breakdown:
- Hooking the Function
- The first line
add_action( 'wp_footer', 'bbloomer_no_ajax_view_cart_button' );
utilizes the WordPressadd_action
function. - This function hooks the
bbloomer_no_ajax_view_cart_button
function to thewp_footer
action. - The
wp_footer
action signifies that thebbloomer_no_ajax_view_cart_button
function will be executed on every WordPress frontend page/post.
- The first line
bbloomer_no_ajax_view_cart_button
- This function is designed to specifically target the button that appears after an AJAX add to cart event in WooCommerce.
wc_enqueue_js
- The line
wc_enqueue_js
is a WooCommerce function used to enqueue (include) JavaScript code. - The JavaScript code provided within the quotation marks is the core functionality of this code snippet.
- The line
- JavaScript Code
- This code snippet utilizes jQuery to target the DOM (Document Object Model) after the document body is loaded (
$( document.body ).on('wc_cart_button_updated', function(){...})
). - It specifically looks for the element with the class
added_to_cart.wc-forward
which is the “View Cart” button that appears after an AJAX add to cart. - When the
wc_cart_button_updated
event is detected (indicating an AJAX add to cart has happened), the JavaScript code removes the targeted element using the.remove()
function.
- This code snippet utilizes jQuery to target the DOM (Document Object Model) after the document body is loaded (
/**
* @snippet Hide "View Cart" @ Woo Shop Page
* @tutorial Get CustomizeWoo.com FREE
* @author Rodolfo Melogli
* @compatible WooCommerce 8
* @community Join https://businessbloomer.com/club/
*/
add_action( 'wp_footer', 'bbloomer_no_ajax_view_cart_button' );
function bbloomer_no_ajax_view_cart_button() {
wc_enqueue_js( "
$( document.body ).on('wc_cart_button_updated', function(){
$('.added_to_cart.wc-forward').remove();
});
" );
}