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.
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.
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.
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)
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
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.
Now, let us save and test in Frontend!
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
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
At this stage, your button should looks like this.
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.
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:
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.
<?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!
6 comments
kirkfall
Hello, do you have any plans on making a pro tutorial for this?
"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."
I want to enable the same style of add to cart button on my single product page.
kirkfall
Hello, I was following this guide and the product loop guide as a trial before purchasing the pro version.
"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"
Where do I select this option?
Another issue: in the bricks builder it displays the proper add to cart radio button that was added from the tutorial. However, on the live site, it displays both the add to cart button and the default woocommerce add to cart button.
Elijah
Hi, Jenn. Thanks for the information.
How can I now use this knowledge to add the ability to add a product option to the cart using ajax? For example, to display a radio button here with a selection of options and the option to order immediately
gustavo
thanks for your post. It's a great help.
I don't know if you could help me, in my case I want to make an AJAX add to letter for variable product where I want to put the id and its specific variation. Can this be done?
Thank you very much in advance
Max
Hi Jenn,
I am using Bricks add-to-cart element which I Ajaxified with the css and data attributes you also mention in your tutorial.
I would be interested in knowing how to control data-quantity value dynamically with JavaScript. Thanks, Max
Jenn Lee
Hi Max,
Basically, you need to listen to 2 different events.
1. Click event on the plus / minus span
2. Input event on the quantity input
3. Create a function to set your button data-quantity attribute value to the quantity input value.
// Example
const setAjaxQty = (e) => {
// some logic to get currentAjaxBtn and currentQtyInput
currentAjaxBtn.setAttribute('data-quantity', currentQtyInput.value )
}
document.querySelector('form.cart .quantity input.qty').addEventListener('input', setAjaxQty )
document.querySelector('form.cart .quantity .action.plus, .quantity .action.minus').addEventListener('click', setAjaxQty )
I am not able to give you the example of full code, because I am not sure how your button structure and the classes like.