How do I automatically add items to my WooCommerce cart?

How do I automatically add items to my WooCommerce cart?

In WooCommerce you can create specific URLs which can then be added to a link which, when clicked, will add the desired products to the users cart and also load a specific page of your choosing.

(Update Jan 2023: There is a plugin which I built which does this for free so read about here before coding your own solution)

In this article I’ll show you how to construct these URLs as well as give you some custom code to build a form which automates this process for the user to some degree so you can remove the technicality of it for those users who are not very technical.

These are very useful for various marketing purposes which allow the user to avoid searching for the products.

What do these links below actually do?

Just in case you’re relatively new to websites the below links, once clicked, will take the user to the page specified (in my examples below this is the /checkout/ page) AND at the same time add the selected products to the cart. So the aim of these links is to get someone to the checkout page as quickly as possible so they can pay.

Table of Contents:

Why use Add to Cart Links in WooCommerce?

The main reason you would want to do this is to hurry people through the checkout process on your site. For example,

  • Some people don’t want to peruse the /shop page in order to view each of the product, choose one and then proceed to checkout.
  • Another use case is that someone contacts you or a sales consultant directly and says “Hey, I need X and Y product” and instead of referring then directly to you can send them an email or a page with the specific links to those products in them already.
  • Yet another example might be to share specific links with specific social media posts so that people can add the specific products you are promoting direct to the cart, while simultaneously loading the checkout page so they can add payment details and hasten the checkout process.

Once they click the link the products (you select) are automatically added to the users cart and you can send them to the checkout (or whatever page you want) where they can simply enter their payment details and hence complete a transaction in less time.

Some house keeping to support you creating your own links

You can create various kinds of Add to Cart Links which are supported by WooCommerce based on the various kinds of products it can have. Below I’ll give you the HTML and Link for each below so you can copy and paste them to your application as you desire.

PROTIP: Make sure you replace the highlighted areas of each to suit your own products and quantities.

Finding the Product ID:

If you need to know the Product ID for the specific product you can find that on this page (assuming WooCommerce is installed already) in your CMS (you’ll need to login to access it). https://yoursite.com/wp-admin/edit.php?post_type=product

You can then look at the product list and look for the ID:1234 on each one.

You can see the ID for each product in the product list as above.

Which page should I redirect to?

In the examples below I have assumed that you want to send the person (once they have clicked the link) to the /checkout/ page but if you, for your own application, want you can change this page to /cart/ or whatever other page you need.

Add to Cart Links

A single product:

https://yoursite.com/checkout/?add-to-cart=123

<a href="https://yoursite.com/checkout/?add-to-cart=123">Purchase Product(s)</a>

A single product with quantity:

https://yoursite.com/checkout/?add-to-cart=123&quantity=3

<a href="https://yoursite.com/checkout/?add-to-cart=123&quantity=3">Purchase Product(s)</a>

Multiple products:

https://yoursite.com/checkout/?add-to-cart=123,987 // each product URL is separated by a comma

<a href="https://yoursite.com/checkout/?add-to-cart=123,987">Purchase Product(s)</a>

Multiple single products and quantities:

https://yoursite.com/checkout/?add-to-cart=123,987&quantity=3,4 // each respective product ID and quantity is separated by a comma

<a href="https://yoursite.com/checkout/?add-to-cart=123,987&quantity=3,4">Purchase Product(s)</a>

Grouped Products:

A grouped product will have its own ID which represents a group of products. From there you will need the product IDs of each individual product which IS WITHIN the grouped product.

PROTIP: This makes sense because in WooCommerce to create a Grouped Product (which has its own ID) is a process of first creating it and then adding specific products (which have their own individual IDs) to it.

https://yoursite.com/checkout/?add-to-cart=123&quantity[987]=3&quantity[456]=1

<a href="https://yoursite.com/checkout/?add-to-cart=123&quantity[987]=3&quantity[456]=1">Purchase Product(s)</a>

Variable Products:

Variable products are those which have various ‘attributes’ that require some customisation from the client. An example might be, a t-shirt which could have different colours and sizes but is essentially the same Product (and related Product ID in WooCommerce). In the example above the size and the colour are ‘attributes’ in WooCommerce.

In order to write Add to Cart links for variable products you need to know not only the Product ID (which can be found as per above instructions) but also the attribute IDs.

In order to find the attributes you need to go to the specific product in the CMS and look there for the attributes. You can search for that product in the CMS on the product page – also described above.

Once you are on the specific product page you can scroll down to the section where it says ‘Product Data”. Select the ‘Variations’ tab. You will then see a list of all the variations (or attributes) and next to each one will be a #33, for example, which will represent the variation_id which you need to use the below links properly.

Variable Products with one Attribute:

https://yoursite.com/checkout/?add-to-cart=123&variation_id=33&attribute_pa_size=small

<a href="https://yoursite.com/checkout/?add-to-cart=123&variation_id=33&attribute_pa_size=small">Purchase Product(s)</a>

Variable Products with two Attributes:

https://yoursite.com/checkout/?add-to-cart=123&variation_id=33&attribute_pa_size=small&attribute_pa_colour=yellow

<a href="https://yoursite.com/checkout/?add-to-cart=123&variation_id=33&attribute_pa_size=small&attribute_pa_colour=yellow">Purchase Product(s)</a>

Variable Products with two attributes and quantity:

https://yoursite.com/checkout/?add-to-cart=123&variation_id=33&quantity=4&attribute_pa_size=small&attribute_pa_colour=yellow

<a href="https://yoursite.com/checkout/?add-to-cart=123&variation_id=33&quantity=4&attribute_pa_size=small&attribute_pa_colour=yellow">Purchase Product(s)</a>

Automate creating ‘Add to Cart’ URLs with a custom form:

PROTIP: The following is a developer level doc and requires some knowledge of coding in a theme or child theme.

What the below code does and does not do from a functionality point of view:

Here is a quick video to show you how the form is meant to work on the front end once you have installed it.

This is a more or less finished version of the code in this section 4 to show you what kind of functionality it gives you.
  • The below code is a ‘shortcode’ and allows you to take the form and embed it on any page or part of your site as you wish. If you aren’t sure how to add a shortcode, no problem, I will go over that in part 3 below either in the CMS or via PHP.
  • Read the notes within this code in order to understand what it’s doing. It’s dangerous to just copy and paste code into your application.
  • The basic functionality which this code provides is…
  • A dynamic form which allows you to add multiple products with multiple quantities of each to a URL. On page load only one product is allowable but there is a button, denoted with a ‘+’ sign which allows you to add more products.
  • It DOES NOT support Grouped and Variable Product types but you could extend it to do that if you wish by changing the AJAX logic which is used in this version of the code. You would want to differentiate between products in the PHP logic of the AJAX request and return different HTML to the user to support the additional info required of the Grouped and Variable Products.

Step 1: Add this jQuery to your application in an appropriate place

PROTIP: You will need to add this code in a particular new file in your theme (or child theme) and the exact location will depend on your application so wherever you add it make sure to note where that is because in the next step you will need to change the PHP path to this file in order for this set of of code to work as a whole.

Step 1.1 Create a new file wherever you want to put JS

I usually create a folder like this, wp-content/your-theme/assets/js/, to store my JS in a theme. So to add the below javascript you could create a new JS file at wp-content/your-theme/assets/js/product-url-form.js to house the below code.

Step 1.2 Add the below JS to your newly created file:

jQuery(document).ready(function($) {

   // checks if a JS variable is empty Returns true if the variable IS EMPTY and false if it IS NOT EMPTY
       function produrlform_empty(variable){

           if( typeof variable == "undefined" || variable == '' || variable == null || variable == 0 ){
               return true;
           }else{
               return false;
           }
       }

	$( "#product_url_form" ).submit(function( event ) {

       event.preventDefault();
       var first_prod = $('#prod_url_select_1').val();
       var url = 'https://yourwebsite.com/checkout/?add-to-cart=';
       var product_segment = '';
       var qty_segment = '';

       // Lets make a product string
           $( ".prod_url_select" ).each(function( index ) {
               
               var product = $(this).val();

               if( !produrlform_empty(product)){

                   if (index === ($('.prod_url_select').length -1)) {
                       product_segment += product;
                   }else{
                       product_segment += product + ',';
                   }
               }
           });

           url += product_segment;

       // Lets make a qty string now
           qty_segment += '&quantity=';
           $( ".prod_url_qty" ).each(function( index ) {
               
               var qty = $(this).val();

               if( !produrlform_empty(qty)){
                   if (index === ($('.prod_url_qty').length -1)) {
                       qty_segment += qty;
                   }else{
                       qty_segment += qty + ',';
                   }
               }
           });
           url += qty_segment;

       $('#urlHolder').val(url);
       $('.copybox').show();
       $('.error_message').html('');
   });

   // Add a new product set of inputs
       $( "#product_url_form #new_product" ).on( 'click', function( event ) {

           event.preventDefault();

           var original = $('#submit_product_url_list').val();
           $('#submit_product_url_list').val('Loading...');
           var first_prod = $('#prod_url_select_1').val();
           if( produrlform_empty(first_prod) ){
               $('p.error_message').html('Select a product from the existing input before adding another please.');
               $('#submit_product_url_list').val(original);
               return;
           }

           var num_selects = 1;
           $( ".prod_url_select" ).each(function( index ) {
               num_selects++;
           });

           $.ajax({
               url: producturlform_ajax_obj.ajaxurl,
               data: {
                   'action': 'producturlform_ajax_request',
                   'num_selects': num_selects,
                   'nonce' : producturlform_ajax_obj.nonce
               },
               success:function(data) {
                   
                   var obj_data = JSON.parse(data);
                   var new_select = obj_data.select_string;

                   $(new_select).appendTo('.product_url_wrapper');
                   $( ".remove_input" ).on( 'click', function( event ) {
                       event.preventDefault();
                       var index = $(this).data('index');
                       $('#prod_qty_set_' + index).remove();
                   });
                   $('.error_message').html('');
                   $('#submit_product_url_list').val(original);
               },
               error: function(errorThrown){
                   console.log(errorThrown);
               }
           });
       });

   // Copy Button JS
       $( "#copy_url" ).on( 'click', function( event ) {
           event.preventDefault();
           var $temp = $("<input>");
           $("body").append($temp);
           $temp.val($('#urlHolder').val()).select();
           document.execCommand("copy");
           $temp.remove();
           $('#copy_url').text('Copied!');
       });
});

Step 2: Add the below PHP code to your functions.php

PROTIP: Make sure to change the code below to reflect the path of the JS file you created in step 1 above. In the below code look for the ‘/path-specific-to-your-application/product-url-form.js’ line to know where to make your alteration.

<?php
//// existing code within your functions.php...
// Add the shortcode function so it recognised by the WP System
add_shortcode('product_url_form_bdd', 'product_url_form_bdd');
// this is the shortcode function
function product_url_form_bdd() {
// we are going to add a bunch of HTML to the $output variable and return it at the end of this function.
// If you want to edit the HTML in the form you can edit the $output variable below
$output = '<div class="container">
<div class="row">
<form autocomplete="off" id="product_url_form">
<p class="error_message"></p>
<div class="product_url_wrapper">
<div class="col col-md-12 mt-2 px-0 prod_qty_set">
<div class="col col-md-4 px-0 mt-2">
<select data-search="true" id="prod_url_select_1" class="prod_url_select" placeholder="Search for product of choice...">
<option value="0">Search for product of choice...</option>';
// the dropdown will have all published products but you could edit the selection by using the get_posts() belo. See - https://developer.wordpress.org/reference/functions/get_posts/
$products = get_posts( array(
'post_type' => 'product',
'numberposts' => -1,
'post_status' => 'publish',
) );
foreach( $products as $product ){
$output .= '<option value="' . $product->ID . '">' . $product->post_title . '</option>';
}
$output .= '</select>
</div>
<div class="col col-md-2 mt-2">
<input  placeholder="Quantity" type="number" class="prod_url_qty" value="1">
</div>
</div>
</div>
<div class="row">
<div class="col col-md-1 mt-2">
<a class="button" href="#" id="new_product">+</a>
</div>
</div>
<div class="col-12 col-md-12 px-0 my-3">
<div class="col-12 col-md-3 px-0 submit_holder">
<input type="submit" value="Get URL" id="submit_product_url_list">
</div>
</div>
</form>
<div class="copybox col-12 col-md-6 px-0 my-3">
<div class="col-12 col-md-12 px-0">
<input type="text" id="urlHolder" value="No value yet"></input>
</div>
<div class="col-12 col-md-4 px-0 my-2">
<a class="button" href="#" id="copy_url">Copy this URL</a>
</div>
</div>
</div>
</div>';
return $output;
}
add_action( 'wp_enqueue_scripts', 'producturlform_ajax_enqueue' );
// You will want to change the /assets/js/product-url-form.js path to the path of your JS file wherever that may be in your particular application
function producturlform_ajax_enqueue() {
if( is_page('product_url_form_bdd') ){
// Enqueue javascript on the frontend.
wp_enqueue_script(
'producturlform-ajax-script',
get_template_directory_uri() . '/path-specific-to-your-application/product-url-form.js', 
array('jquery')
);
// The wp_localize_script allows us to output the ajax_url path for our script to use.
wp_localize_script(
'producturlform-ajax-script',
'producturlform_ajax_obj',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce('ajax-nonce')
)
);
}
}
add_action( 'wp_ajax_producturlform_ajax_request', 'producturlform_ajax_request' );
// If the user clicks the button with '+' symbol this function is called and adds another input and quantity set of fields for them to select another product.
function producturlform_ajax_request() {
if($_REQUEST['num_selects']){ 
$num_selects = sanitize_text_field($_REQUEST['num_selects']); 
}
$products = get_posts( array(
'post_type' => 'product',
'numberposts' => -1,
'post_status' => 'publish',
) );
$output = array();
$output['select_string'] = '<div class="col col-md-12 my-2 px-0 prod_qty_set" id="prod_qty_set_' . $num_selects . '"><div class="col col-md-4 px-0 mt-2"><select id="prod_url_select_' . $num_selects . '" class="prod_url_select" placeholder="Search for product of choice...">';
$output['select_string'] .= '<option value="0">Search for product of choice...</option>';
foreach( $products as $product ){
$output['select_string'] .= '<option value="' . $product->ID . '">' . $product->post_title . '</option>';
}
$output['select_string'] .= '</select></div><div class="col col-md-2 mt-2"><input  placeholder="Quantity" type="number" class="prod_url_qty" value="1"></div><div class="col col-md-1 mt-2"><a href="#" class="remove_input" data-index="' . $num_selects . '">x</a></div></div>';
print_r(json_encode($output));
die();
}
function webroom_add_multiple_products_to_cart( $url = false ) {
// Make sure WC is installed, and add-to-cart qauery arg exists, and contains at least one comma.
if ( ! class_exists( 'WC_Form_Handler' ) || empty( $_REQUEST['add-to-cart'] ) || false === strpos( $_REQUEST['add-to-cart'], ',' ) ) {
return;
}
// Remove WooCommerce's hook, as it's useless (doesn't handle multiple products).
remove_action( 'wp_loaded', array( 'WC_Form_Handler', 'add_to_cart_action' ), 20 );
$product_ids = explode( ',', $_REQUEST['add-to-cart'] );
$count       = count( $product_ids );
$number      = 0;
foreach ( $product_ids as $id_and_quantity ) {
// Check for quantities defined in curie notation (<product_id>:<product_quantity>)
$id_and_quantity = explode( ':', $id_and_quantity );
$product_id = $id_and_quantity[0];
$_REQUEST['quantity'] = ! empty( $id_and_quantity[1] ) ? absint( $id_and_quantity[1] ) : 1;
if ( ++$number === $count ) {
// Ok, final item, let's send it back to woocommerce's add_to_cart_action method for handling.
$_REQUEST['add-to-cart'] = $product_id;
return WC_Form_Handler::add_to_cart_action( $url );
}
$product_id        = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $product_id ) );
$was_added_to_cart = false;
$adding_to_cart    = wc_get_product( $product_id );
if ( ! $adding_to_cart ) {
continue;
}
$add_to_cart_handler = apply_filters( 'woocommerce_add_to_cart_handler', $adding_to_cart->get_type(), $adding_to_cart );
// Variable product handling
if ( 'variable' === $add_to_cart_handler ) {
woo_hack_invoke_private_method( 'WC_Form_Handler', 'add_to_cart_handler_variable', $product_id );
// Grouped Products
} elseif ( 'grouped' === $add_to_cart_handler ) {
woo_hack_invoke_private_method( 'WC_Form_Handler', 'add_to_cart_handler_grouped', $product_id );
// Custom Handler
} elseif ( has_action( 'woocommerce_add_to_cart_handler_' . $add_to_cart_handler ) ){
do_action( 'woocommerce_add_to_cart_handler_' . $add_to_cart_handler, $url );
// Simple Products
} else {
woo_hack_invoke_private_method( 'WC_Form_Handler', 'add_to_cart_handler_simple', $product_id );
}
}
}
// Fire before the WC_Form_Handler::add_to_cart_action callback.
add_action( 'wp_loaded', 'webroom_add_multiple_products_to_cart', 15 );
/**
* Invoke class private method
*
* @since   0.1.0
*
* @param   string $class_name
* @param   string $methodName
*
* @return  mixed
*/
function woo_hack_invoke_private_method( $class_name, $methodName ) {
if ( version_compare( phpversion(), '5.3', '<' ) ) {
throw new Exception( 'PHP version does not support ReflectionClass::setAccessible()', __LINE__ );
}
$args = func_get_args();
unset( $args[0], $args[1] );
$reflection = new ReflectionClass( $class_name );
$method = $reflection->getMethod( $methodName );
$method->setAccessible( true );
//$args = array_merge( array( $class_name ), $args );
$args = array_merge( array( $reflection ), $args );
return call_user_func_array( array( $method, 'invoke' ), $args );
}

Step 3: Add the shortcode to a page or code segment within your site

As this is a shortcode you can add this in the CMS on the page or post editor or via PHP if you want to do it that way.

Step 3.1 Adding the shortcode in the CMS

Navigate to a page in your CMS and add, [product_url_form_bdd] , to the content area of the page. Then save it. Open the URL for the page and view the results as per the next step.

Add the shortcode to the content area of a new page. Save it and then preview the page before moving onto review in step 4.

Step 3.2 Adding the shortcode via PHP

If you want to add this form via PHP and not in the CMS then you can do something like this in your PHP application.

// print the form out in your PHP code
echo do_shortcode("[product_url_form_bdd]");

Step 3.3 Wrapping Up

You should now be able to load the front end of your site and see the form as it was shown above in the video.

Learn to customize WooCommerce Fully with an online Udemy course

If you’d like to know more about how to customize WooCommerce completely check out these courses from Udemy which are low cost, online and have been completed by thousands of people.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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