Add to cart

How to add a shopping cart button to your website

Today, when you have a great product or service to sell, it’s easy enough to drum up interest online. You can build your own website, blog about your product and use social media to promote your product launch. Once you have your own website you are ready to take on a world of customers and start selling. But then you realize one thing is missing — the key ingredient of any e-commerce site. You need an “Add to Cart” button so you can actually collect money.

Ecwid is powerful enough to build an entire online marketplace, integrating a shopping cart directly into your website and flexible enough to sell just a single product in a blog post. Once you have signed up for a free Ecwid account and have added your products to the Catalog, it’s time to start selling. Here is how to use Ecwid’s Add to Cart button functionality on your website.

Embed a custom “Add to Cart” button in 3 steps

1. Find your product’s embed code.

From your Catalog, choose the product you want to sell. Go to the product page and select the tab for “Embed product.”

2. Choose your product properties.

You have a few options to display above your “Add to Cart” button:

  • Product picture
  • Title
  • Price
  • Options
  • Quantity

If you prefer the simple route, select just the button property.

3. Copy and paste the embed code into your site.

Copy the HTML embed code, and using a code editor, paste it into a page on your website. Save and preview your new page. Your “Add to Cart” button should appear on your site.

Now that you have added your product widget and “Add to Cart” button, you need it to match the rest of your page. Unlike other e-commerce widgets, which can look clunky and out-of-place, Ecwid allows you to seamlessly maintain one cohesive design across your website.

It’s easy to customize the look and feel of your shopping cart button. Best of all, there’s no need to wrangle with your website’s backend. You can make changes directly from your Ecwid control panel by plugging in some simple CSS styles. I’ll show you how to change your button’s color, text and more.

Customize the “Add to Cart” button color

  1. Once you’ve decided what color you want your button to be, find the corresponding hex code from your website theme or a color generator. You can also choose custom colors for when your customer is hovering over or clicking the button.
  2. Go to Control Panel → Settings → Design → CSS Themes. Create a new CSS theme or open your active custom theme.
  3. Paste this code into your custom theme and replace the hex codes in each style.

Steps to add custom data for a product during ‘add to cart’:

1. Add the custom data in session on click of ‘Add to cart’:

On Click of ‘Add To Cart’ button make an ajax call to store the custom entered data in session

2. Add the Custom Data from Custom Session to WooCommerce Session:

In Step 1 we added the custom data to our created session on click of ‘Add To Cart’ button. After clicking on add to cart the products gets added to cart and WooCommerce session gets created for it. In this step, we will add our custom data to WooCommerce data for this “particular product”.


3. Add the custom data to WooCommerce cart object

WooCommerce creates a cart object to display all the products added to cart. We need to add the custom information in the cart during checkout. So add the information in cart object.

4. Display Custom data in cart and Checkout page

The custom data is already present in cart object, so you can display it in the cart where the product is displayed.

5. Add custom data as Metadata to Order Items table

We need to store the custom data in our Order Items MetaData table so that admin can view the information entered and deliver the products accordingly.

6. Remove User Custom Data, if Product is Removed from Cart

We also need to remove the custom data if the user removes the product from cart.

7. Additional price based on custom data

Sometimes you may need to calculate an additional price based on entered information. So here we can calculate the price.

Creating the structure

The main HTML structure is an unordered list. Each list item contains an unordered list (product image slider), a

(with the Add To Cart button and the product customization options) and a (with product title and price).

<ul class="cd-gallery">  <li>  <div class="cd-single-item">  <a href="#0">  <ul class="cd-slider-wrapper">  <li class="selected"><img src="img/thumb-1.jpg" alt="Preview image"></li>  <li><img src="img/thumb-2.jpg" alt="Preview image"></li>  <!-- other product images here -->  </ul>  </a>   <div class="cd-customization">  <div class="color" data-type="select">  <ul>  <li class="color-1 active">color-1</li>  <li class="color-2">color-2</li>  <!-- other product colors here -->  </ul>  </div> 				  <div class="size" data-type="select">  <ul>  <li class="small active">Small</li>  <li class="medium">Medium</li>  <!-- other product sizes here -->  </ul>  </div>   <button class="add-to-cart">  <em>Add to Cart</em>  <svg x="0px" y="0px" width="32px" height="32px.  

oduct Name</a></b> <em>$9.99</em> </div> <!-- cd-item-info --> </li> <!-- other list items here --> </ul> <!-- cd-gallery -->

Adding style

Let’s start from the product slider. By default, the list items are in absolute position and translated to the right (outside their .cd-gallery parent) so they are not visible. We then used 2 classes to properly style them: .selected (added to the first list item – visible product image) and .move-left ( product image on the left — not visible).

.cd-slider-wrapper {  position: relative;  overflow: hidden; } .cd-slider-wrapper li {  position: absolute;  top: 0;  left: 0;  visibility: hidden;  /* by default, move the product image to the right*/  transform: translateX(100%);  transition: transform 0.3s 0s, visibility 0s 0.3s; } .cd-slider-wrapper li.selected {  /* this is the visible product image */  position: relative;  visibility: visible;  z-index: 1;  transform: translateX(0);  transition: transform 0.3s 0s, visibility 0s 0s; } .cd-slider-wrapper li.move-left {  /* move the product image to the left */  transform: translateX(-100%); }  

About the product customization options: the .cd-customization element is shown when a user hovers over the product; it’s in absolute position and placed at the bottom of its .cd-single-item parent element.
To create the customization options (color and size), we used two different <ul> elements, both wrapped in a div[data-type="select"] (div.size and div.color). The <ul> element is in absolute position and centered relative to its parent while the div[data-type="select"] has a fixed height (34px) and an overflow: hidden. Each list item inside the unordered list has a height equal to the div[data-type="select"] so that, by default, only the selected option is visible.
When a user clicks one of the two customization options, the overflow property of the div[data-type="select"] is set to visible so that the entire <ul> element is shown.

.cd-customization {  position: absolute;  left: 0;  bottom: 0;  width: 100%;  visibility: hidden;  opacity: 0; }  .no-touch .cd-.  

{ /* color/size list open - make ul element visible */ overflow: visible; }

To make sure that the selected <li> item is always visible, we had to rearrange the list items inside their <ul> parent according to the selected option. To do that, we created the .selected-n class (where n is the item selected). For example, the .selected-3 class is added to the div[data-type="select"] when the third list item is selected:

.cd-customization .color.selected-3 ul li:first-of-type,  .cd-customization .size.selected-3 ul li:first-of-type {  /* third option selected in the ul.color/ul.size list */  transform: translateY(0); } .cd-customization .color.selected-3 ul li:nth-of-type(2),  .cd-customization .size.selected-3 ul li:nth-of-type(2) {  transform: translateY(100%); } .cd-customization .color.selected-3 ul li:nth-of-type(3),  .cd-customization .size.selected-3 ul li:nth-of-type(3) {  transform: translateY(-100%); }  

About the Add To Cart animation: the .add-to-cart button is composed by an <em> (button text message) and a svg (check icon). By default, the svg is not visible (it’s moved to the right, outside the button).
When the product is added to the cart, the .is-added class is added to the .add-to-cart button: the <em> (text) is hidden (moved to the left), while the svg is moved  back inside the button, and the drawing animation starts:

.cd-customization .add-to-cart em {  /* this is the button text message */  position: absolute;  top: 0;  left: 0;  width: 100%;  height: 100%; } .cd-customization .add-to-cart svg {  /* this is the check icon */  position: absolute;  left: 50%;  top: 50%;  width: 100%;  /* move the icon on the right - outside the button */  transform: translateX(50%) translateY(-50%); } .cd-customization em {  /* product added to the cart - hide text message on the left with no transition*/  color: transparent;  transform: translateX(-100%); } .cd-customization svg {  /* product added to the cart - move the svg back inside the button */  transform: translateX(-50%) translateY(-50%); }

About the svg drawing animation, we used the two svg attributes stroke-dasharray

and stroke-dashoffset. The first one lets you specify dash length and gaps, while the second one lets you change where the dasharray starts. In our case, we set stroke-dasharray=»19.79 19.79″ and stroke-dashoffset=»19.79″ (where 19.76 is the path length):

<svg x="0px" y="0px" width="32px" height="32px" viewBox="0 0 32 32">  <path stroke-dasharray="19.79 19.79" stroke-dashoffset="19.79" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="square" stroke-miterlimit="10" d="M9,17l3.9,3.9c0.1,0.1,0.2,0.1,0.3,0L23,11"/> </svg>

and then animate the dashoffset value to 0 to create the drawing animation.

If you’re interested in more details about animating svg icons, you can give a look at what we did in the article Animated SVG Icon.

Note: to animate the dashoffset value, we could have used css transitions (rather then using the animate() jQuery method), but unfortunately IE11 seems to have a bug with transitions on some svg properties.

Last note for touch devices: we used Modernizer to target touch devices and add a .cd-customization-trigger (settings icon) to trigger element visibility.

Events handling

When a user interacts with one of the product customization options (e.g, the colors option), the .hover class is added to the corresponding .cd-single-item

element. This class sets the .cd-customization element to visible, so that it doesn’t disappear if the cursor leaves the product (we assumed that the user is interested in the product since he has interacted with it, and doesn’t want to lose the options if he accidentally leaves the product). For the same reason, the .hover class is removed from all the other products (so that user can focus only on the product he is interacting with). The resetCustomization() function has been defined to do that:

function resetCustomization(selectOptions) {  //add .hover class to the item user is interacting with  //close ul.color/ul.size if they were left open and user is not interacting with them anymore  //remove the .hover class from items if user is interacting with a different one  selectOptions.siblings('[data-type="select"]').removeClass('is-open').end().parents('.cd-single-item').addClass('hover').parent('li').siblings('li').find('.cd-single-item').removeClass('hover').end().find('[data-type="select"]').removeClass('is-open'); }

Besides, we used jQuery to implement the product slider (different color images) and the updateCart() function (to update the number of products added to the cart).

Add a product to the cart.

Это метод класса: WC_Cart

Хуки из метода

Строку/true/false. $cart_item_key


$WC_Cart = new WC_Cart(); $var = $WC_Cart->add_to_cart( $product_id, $quantity, $variation_id, $variation, $cart_item_data );
contains the id of the product to add to the cart.
По умолчанию: 0
contains the quantity of the item to add.
По умолчанию: 1
ID of the variation being added to the cart.
По умолчанию: 0
attribute values.
По умолчанию: array()
extra cart item data we want to pass into the item.
По умолчанию: array()

Код WC Cart::add to cart: woocommerce/includes/class-wc-cart.php VER 3.5.3

<?php public function add_to_cart( $product_id = 0, $quantity = 1, $variation_id = 0, $variation = array(), $cart_item_data = array() ) { 	try { 		$product_id = absint( $product_id ); 		$variation_id = absint( $variation_id );  		// Ensure we don't add a variation to the cart directly by variation ID. 		if ( 'product_variation' === get_post_type( $product_id ) ) { 			$variation_id = $product_id; 			$product_id = wp_get_post_parent_id( $variation_id ); 		}  		$product_data = wc_get_product( $variation_id ? $variation_id : $product_id ); 		$quantity = apply_filters( 'woocommerce_add_to_cart_quantity', $quantity, $product_id );  		if ( $quantity <= 0 || ! $product_data || 'trash' === $product_data->get_status() ) { 			return false; 		}  		// Load cart item data - may be added by other plugins. 		$cart_item_data = (array) apply_filters( 'woocommerce_add_cart_item_data', $cart_item_data, $product_id, $variation_id, $quantity );  		// Generate a ID based on product ID, variation ID, variation data, and other cart item data. 		$cart_id = $this->generate_cart_id( $product_id, $variation_id, $variation, $cart_item_data );  		// Find the cart item key in the existing cart. 		$cart_item_key = $this->find_product_in_cart( $cart_id );  		// Force quantity to 1 if sold individually and check for existing item in cart. 		if ( $product_data->is_sold_individually() ) { 			$quantity = apply_filters( 'woocommerce_add_to_cart_sold_individually_quantity', 1, $quantity, $product_id, $variation_id, $cart_item_data ); 			$found_in_cart = apply_filters( 'woocommerce_add_to_cart_sold_individually_found_in_cart', $cart_item_key && $this->cart_contents[ $cart_item_key ]['quantity'] > 0, $product_id, $variation_id, $cart_item_data, $cart_id );  			if ( $found_in_cart ) { 				/* translators: %s: product name */ 				throw new Exception( sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', wc_get_cart_url(), __( 'View cart', 'woocommerce' ), sprintf( __( 'You cannot add another "%s" to your cart.', 'woocommerce' ), $product_data->get_name() ) ) ); 			} 		}  		if ( ! $product_data->is_purchasable() ) { 			throw new Exception( __( 'Sorry, this product cannot be purchased.', 'woocommerce' ) ); 		}  		// Stock check - only check if we're managing stock and backorders are not allowed. 		if ( ! $product_data->is_in_stock() ) { 			/* translators: %s: product name */ 			throw new Exception( sprintf( __( 'You cannot add &quot;%s&quot; to the cart because the product is out of stock.', 'woocommerce' ), $product_data->get_name() ) ); 		}  		if ( ! $product_data->has_enough_stock( $quantity ) ) { 			/* translators: 1: product name 2: quantity in stock */ 			throw new Exception( sprintf( __( 'You cannot add that amount of &quot;%1$s&quot; to the cart because there is not enough stock (%2$s remaining).', 'woocommerce' ), $product_data->get_name(), wc_format_stock_quantity_for_display( $product_data->get_stock_quantity(), $product_data ) ) ); 		}  		// Stock check - this time accounting for whats already in-cart. 		if ( $product_data->managing_stock() ) { 			$products_qty_in_cart = $this->get_cart_item_quantities();  			if ( isset( $products_qty_in_cart[ $product_data->get_stock_managed_by_id() ] ) && ! $product_data->has_enough_stock( $products_qty_in_cart[ $product_data->get_stock_managed_by_id() ] + $quantity ) ) { 				throw new Exception( 					sprintf( 						'<a href="%s" class="button wc-forward">%s</a> %s', 						wc_get_cart_url(), 						__( 'View cart', 'woocommerce' ), 						/* translators: 1: quantity in stock 2: current quantity */ 						sprintf( __( 'You cannot add that amount to the cart &mdash; we have %1$s in stock and you already have %2$s in your cart.', 'woocommerce' ), wc_format_stock_quantity_for_display( $product_data->get_stock_quantity(), $product_data ), wc_format_stock_quantity_for_display( $products_qty_in_cart[ $product_data->get_stock_managed_by_id() ], $product_data ) ) 					) 				); 			} 		}  		// If cart_item_key is set, the item is already in the cart. 		if ( $cart_item_key ) { 			$new_quantity = $quantity + $this->cart_contents[ $cart_item_key ]['quantity']; 			$this->set_quantity( $cart_item_key, $new_quantity, false ); 		} else { 			$cart_item_key = $cart_id;  			// Add item after merging with $cart_item_data - hook to allow plugins to modify cart item. 			$this->cart_contents[ $cart_item_key ] = apply_filters( 				'woocommerce_add_cart_item', array_merge( 					$cart_item_data, array( 						'key' => $cart_item_key, 						'product_id' => $product_id, 						'variation_id' => $variation_id, 						'variation' => $variation, 						'quantity' => $quantity, 						'data' => $product_data, 						'data_hash' => wc_get_cart_item_data_hash( $product_data ), 					) 				), $cart_item_key 			); 		}  		$this->cart_contents = apply_filters( 'woocommerce_cart_contents_changed', $this->cart_contents );  		do_action( 'woocommerce_add_to_cart', $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data );  		return $cart_item_key;  	} catch ( Exception $e ) { 		if ( $e->getMessage() ) { 			wc_add_notice( $e->getMessage(), 'error' ); 		} 		return false; 	} }

Add to cart?

Adding an item to their cart refers to the action a visitor of a web shop takes when they put an item into their digital shopping cart. This action is usually performed by clicking a designated button on either the category overview page or the product detail page. Common variations include Add to Bag and Add to Basket. These phrases are then used in combination with respectively a Shopping Bag and Shopping Basket used on the website.

The ultimate micro conversion

Getting a visitor to click an Add to Cart button is an important micro conversion. Its significance stems mainly from the fact that it is often the first commitment that a visitor makes towards becoming one of your customers. Because this is such an important step for a visitor to take, I would urge you to set up event tracking for this action if you haven’t already done so.

Before the click or tap

Call-To-Action button

One of the most important aspects of determining whether or not a visitor will add an item to their cart is the Call-To-Action (CTA) button.


While it’s okay (even advised) to make the button stand out in regards to the shape, try not to go overboard with this. Make sure the button still has enough affordance to intuitively make people realize that this is the element that they should be clicking on.


Most importantly you shouldn’t buy into the myth that one particular color of CTA button will always perform better than all the others. While it may be true that a green button performs best on website X (particularly if the rest of the design is mainly red), it would probably perform poorly on a website whose design is predominantly green-colored. In other words, it’s not that actual color that’s important, it is the contrast compared to other elements on the page.


Similar to the item above, while you should make sure the item stands out, at the same time you should also be wary not to make it too big. After all, you wouldn’t want a visitor to overlook your CTA button because he is mistaken it for a banner now, wouldn’t you? Also, make sure to test the button on mobile and tablet to make sure it look well-proportioned compared to the other elements on those devices as well.


The optimal position of the CTA button on the product page can be trickier than it might seem. Whenever possible, the web designer should set up the visual design in a way that the CTA and price are in close proximity to each other. This in order to prevent the visitor from having to look back and forth to know for sure the price they will be paying when they click the button.

Above or below the fold

With regards to the fold, you should consider the complexity of the product you’re selling. If the product needs to be explained to visitors first, try placing the CTA below the fold. In instances where the product is pretty self-explanatory, try placing the CTA above the fold. Of course, whenever possible you should use A/B testing to verify if this rule of thumb works best for your target audience as well.


I’ve seen instances where changing the text on a CTA button increased Click-Through-Rate (CTR) by over 50% and conversion by more than 10%. One of the most important aspects to keep in mind here is the level of commitment or ‘no return’ a button implies. While ‘Buy Now’ represents a high level of commitment (in fact, my credit card might be charged immediately), the text ‘Add to Cart’ on the other hand, implies that additional steps need to be taken before there is a point of no return.

After the click or tap


Unfortunately, the first thing that happens after you click on a CTA is that an error will be shown. Most often these errors will alert you to the fact that you have forgotten to select one or more attributes of the item you intend to buy. Such attributes include size, color or amount.

In order to get visitors past this hurdle as soon as possible, make sure the error can’t be easily overlooked, and perhaps, more importantly, tells them clearly how to proceed. The error ‘Something went wrong’ is not helpful, ‘Please select a size first’ is.

Animation, notification or popup

After a visitor clicks the button, they should be notified that the item they intend to buy was added successfully to their shopping cart. As it turns out, there are quite a few ways of doing this.

Graham Charlton sums up the matter at hand accurately in his article on Econsultancy:

Graham Charlton — Editor in Chief at ClickZ Global

Graham Charlton» />

“I think the best approach to this will depend very much on the type of e-commerce site and, of course, it makes sense for retailers to test these variations until they find the best solution.

It does make sense to have a clear indication that an item has been added to the basket, and to show the next steps in the process.”

Goals and data

By looking closely at your goals and data, you might even be able to distil the optimal solution for your website. For instance, you might ask yourself these questions:

  • What % of visitors are buying more than one item in a single transaction?
  • How likely is it that visitors would add more items if it were easier to do so?
  • Are you aiming for maximum lifetime value, average order value, the number of transactions?

Redirect to cart or continue shopping?

If it’s likely that the vast majority of visitors will only order one type of items per transaction, it might be best to redirect visitors to your shopping cart and show a success notification there. However, if the data shows visitors are often adding more items per transaction, consider showing an inline popup on the product page to notify them of their successfully updated cart.


Summarizing the findings above: make sure your button stands out from the rest of the design in terms of both color, size and shape. However, make sure visitors on all types of devices will still clearly recognize your CTA element as a button they can click on.

For shops that often have visitors buying several different items per transaction: show an inline popup on the product page, and allow the visitor to continue shopping. If, however, your visitors will most likely buy just one item per transaction: take them to your shopping cart and show a success notification there.

Dutch translation: Verbeter je ‘Plaats in Winkelwagen’ Conversie Ratio

You May Also Like

About the Author: admind

Добавить комментарий

Ваш e-mail не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.