50% discount on BricksLabs Pro Membership Lifetime Access. Use coupon: GOBRICKS

Create A Customizable AJAX Add To Cart Button In Bricks Builder

customizable-ajax-add-to-cart-button

In Bricks, you can simply create an Add To Cart button from a dynamic data / function {woo_add_to_cart}. This button supports AJAX as well if you activate the Enable AJAX add to cart buttons on archives in WooCommerce > Settings > Products > Add to cart behaviour.

Activate AJAX add to cart in WooCommerce settings page

Since we are using a visual page builder, why don’t we create this in the builder and so we can style and customize it like a boss?

In this tutorial, I will place my AJAX add to cart button in my custom product loop template. Please feel free to read the product loop tutorial if you want to build yours too.

My Own AJAX add to cart button

Step 1: Bricks Button Element

Important Note

If you are following my product loop tutorial, remember to remove the Outer wrapper link. It might break your layout if link wraps in another link / button wraps in another button

Just add a Button element in the product loop template.

New button at the bottom of my loop

In CONTENT tab, put in your text and icon. For the LINK settings, Link type set to External URL, URL cannot be blank. At least a # to make the button clickable. Best is follow mine so it will populate a dynamic add-to-cart URL. (This doesn’t affects the AJAX function)

URL cannot be empty! At least a # or follow my setting.

Step 2: Transform Normal Button To AJAX Add To Cart

At this stage, your button just behave like a normal one, either clicking it brings you to top of the page because your are using anchor URL (#). If you use ?add-to-cart=post_id in the button URL, this will successfully add the product to cart but it’s not AJAX way.

It’s quite easy to transform the native button to WooCommerce AJAX add to cart. Just need to add some CSS classes and custom attributes will do!

Heads to STYLE tab of the button, set CSS classes as add_to_cart_button ajax_add_to_cart

Remember to separate the classes by space.

Add Attributes:

  • data-quantity : Should set as 1, so the button will add 1 quantity of the current product to cart. To control this value dynamically, you can use JavaScript solution but I am not going to cover in this tutorial.
  • data-product_id: The product id when making AJAX add to cart. Use dynamic post_id to dynamically set it. Of course gonna be in a loop, otherwise the post_id always the same. Check my tutorial for WooCommerce Product Loop Template if you don’t know what I am talking about.
  • aria-label: This is for accessibility.
data-quantity
data-product_id
aria-label

Now, let us save and test in Frontend!

AJAX works! Need improvement.

It works, but we got 2 issues to fix.

  • No indication when AJAX processing and completed.
  • For variable products, it might added successfully but the added product doesn’t has selected option.

Step 3: AJAX Indication

We can use jQuery to hook on WooCommerce events (WooCommerce is still using jQuery). When making call, I will change the “Add Cart” text to “Adding”. When AJAX completed, change it to “Added”.

2022 Aug 17 Update: You can use the same event to redirect visitor to checkout page. Just act like a Buy Now button.

Since this jQuery might be executing in anywhere, I will place my code in Bricks > Settings > Custom Code > Body (footer) scripts

Bricks > Settings > Custom Code > Body (footer) scripts

Important Note

Please don’t use Code element if you are inside a loop unless it’s a special requirement and you know what you are doing. Imagine how many duplicated codes will be rendering in frontend.

<script>
(($)=>{
	$(document).ready(()=>{

		// When Adding To Cart
		$('body').on('adding_to_cart', (e, button, data)=>{
			// Change my Text to "Adding". I use lastChild because firstChild is my Icon
			button[0].lastChild.textContent = "Adding..."
		});
		
		// When Added To Cart
		$('body').on('added_to_cart', (e, fragments, cart_hash, button)=>{
			// Change my Text to "Added"
			button[0].lastChild.textContent = "Added"
		});
	})
})(jQuery)
</script>

Buy Now Button JavaScript Example

// Example to redirect visitor to checkout page after add to cart
// Just change your button text to Buy Now if necessary
$('body').on('added_to_cart', (e, fragments, cart_hash, button)=>{
	// You can use setTimeout to delay redirection if necessary
	setTimeout( function() {
		window.location.href = `${window.location.origin}/checkout`
	}, 800 )
});

To style our button, we can make use loading and added CSS classes which will be injected by WooCommerce while making AJAX call. These 2 classes will be added on the button element.

Below CSS code added on my custom button.

root.loading i {
  -webkit-animation: spin 1s linear infinite;
  animation: spin 1s linear infinite;
}

root.loading i::before {
  content: "\e619";

}

root.added i::before {
  content: "\e64d"
}

Note that I change the icon content to \e619 and \e64d because I am using Themify icons. You can replace them as you like. This CSS part can be adjusted as you like. The spin animation comes from Bricks frontend.min.css

AJAX button CSS

At this stage, your button should looks like this.

Better user experience right?

Step 4: Dynamically Display Button

To avoid errors while adding variable product to cart via AJAX, the best way is display another normal button to direct visitor to the variable product’s page.

Create another simple button below the AJAX add to cart button.

New button
Normal button just set the link to product post_url
2 buttons in the product loop now

Write a simple function in your functions.php or via WPCodebox plugin. This will return True or False dynamically.

<?php

function itchy_is_simple_product() {
	global $product;
	return is_a( $product, 'WC_Product_Simple' );
}


?>

And you can choose either 1 method below to use this function.

Method A: Conditional Visibility Plugin (Unofficial)

I wrote a free conditional display plugin for Bricks in June 2022. You can use it to show or hide the button in Builder mode. Very handy if you are using dynamic data directly like MetaBox or ACF custom fields as the condition comparison values.

Configure the condition in ITCHY ADVANCED tab:

Conditional settings on AJAX button

Conditional settings for normal button

Method B: bricks/element/render Filter

If you prefer coding way, then copy below code into functions.php or via WPCodeBox. Remember to change the element IDs to yours.

Find your element ID
<?php

add_filter( 'bricks/element/render', 'itchycode_conditional_display_buttons', 10, 2 );

function itchycode_conditional_display_buttons( $show, $element ) {
	// Replace your button IDs here
	if( $element->id !== 'qlnmvz' &&  $element->id !== 'rsipdc') return $show;
	
	return itchy_is_simple_product();
}

Check in Frontend, it’s perfect now!

Perfect!

Leave the first comment