WooCommerce: Create Custom Link to Add 2 or More Variations to Cart

WooCommerce: Create Custom Link to Add 2 or More Variations to Cart

Share

Introduction

As we navigate the realm of e-commerce development, we come across a variety of tools designed to optimize our online stores. In the vast universe of WordPress functionalities, there lies a potent PHP function that allows the addition of product variations to a shopping cart directly from a URL. This ingenious functionality, facilitated by WooCommerce, is instrumental in creating more engaging and user-friendly e-commerce experiences.

Before we dive into the mechanics of the function, it’s worth noting that the appearance and functionality of the ‘notice’ feature may vary based on your website’s theme. Not all themes are built the same, and some may handle these notifications differently. Always ensure to test on your specific theme to verify the end result.

First let’s look at the function itself:

function add_variations_to_cart_from_url() {
    if (isset($_GET['add_to_cart_m'])) {
        $product_id = absint($_GET['add_to_cart_m']);
        $variation_ids = isset($_GET['var']) ? explode(',', $_GET['var']) : array();

        if ($product_id && !empty($variation_ids)) {
            foreach ($variation_ids as $variation_id) {
                WC()->cart->add_to_cart($product_id, 1, $variation_id);
            }

            // Get the product URL
            $product_url = get_permalink($product_id);

            // Get the product title
            $product_title = get_the_title($product_id);

            // Set a notice to indicate the product was added to the cart
            wc_add_notice(sprintf('<a href="%s" class="button wc-forward">%s</a> has been added to your cart.', esc_url(wc_get_cart_url()), $product_title), 'success');

            // Redirect to the product URL with the notice
            wp_safe_redirect(add_query_arg('notice', 'added_to_cart', $product_url));
            exit;
        }
    }
}
add_action('template_redirect', 'add_variations_to_cart_from_url');

A Deep Dive into the Function

To understand the nuances of this WordPress function, let’s dissect the following PHP code:

function add_variations_to_cart_from_url() {
    if (isset($_GET['add_to_cart_m'])) {
        $product_id = absint($_GET['add_to_cart_m']);
        $variation_ids = isset($_GET['var']) ? explode(',', $_GET['var']) : array();

The Importance of URL Parameters

In this PHP function, the URL parameters play a pivotal role in directing the flow of the program. Here, add_to_cart_m and var are key.

  • add_to_cart_m: Represents the product ID, serving as a unique identifier for the product intended to be added to the cart.
  • var: Specifies the variations of the product. This data, delineated by commas in the URL, is parsed and stored as an array.

To locate the product ID, head to your WordPress admin dashboard’s product list. By hovering over a product, the link displayed at the bottom of your browser will end with the product ID. To find the product variation ID, navigate to the specific product’s edit page, go to the ‘Product data’ box, select the ‘Variations’ tab, and hover over the variation to view the ID at the end of the link.

Adding Product Variations to the Cart

if ($product_id && !empty($variation_ids)) {
            foreach ($variation_ids as $variation_id) {
                WC()->cart->add_to_cart($product_id, 1, $variation_id);
            }

Following the identification of the product and its variations, the function iterates through each variation. Using WooCommerce’s add_to_cart function, one unit of each variation is added to the cart.

Fetching Product Details and Crafting User Notification

// Get the product URL
            $product_url = get_permalink($product_id);

            // Get the product title
            $product_title = get_the_title($product_id);
            
            // Set a notice to indicate the product was added to the cart
            wc_add_notice(sprintf('<a href="%s" class="button wc-forward">%s</a> has been added to your cart.', esc_url(wc_get_cart_url()), $product_title), 'success');

The function then retrieves the product’s URL and title using WordPress’s built-in functions. These details are then incorporated into a user notification that signals the successful addition of the product to the cart. The notice also includes a link leading the user to the cart.

Redirecting the User

// Redirect to the product URL with the notice
            wp_safe_redirect(add_query_arg('notice', 'added_to_cart', $product_url));
            exit;
        }
    }
}
add_action('template_redirect', 'add_variations_to_cart_from_url');

Finally, the function performs a safe redirect, guiding the user back to the product page. It adds a ‘notice’ parameter in the URL, signifying that the product was successfully added to the cart. This function is affixed to WordPress’s ‘template_redirect’ action, executing before the template file is loaded.

Constructing the Magic URL

Understanding the technicalities behind the function is half the battle won. The next key step lies in successfully implementing this knowledge and creating a URL that adds product variations to the cart. Let’s delve into the nitty-gritty of URL construction.

The URL structure relies heavily on the two key parameters we have discussed: add_to_cart_m and var. The former represents the product ID, while the latter specifies the variations.

In the URL, the parameters are added after your website domain, following this structure:

https://yoursite.com/?add_to_cart_m=123&var=111,222

Here, PRODUCT_ID should be replaced with the actual product ID, and VARIATION_ID_1,VARIATION_ID_2,... should be replaced with the desired variation IDs, separated by commas.

To illustrate this, let’s consider, the product ID is 656, and you have two variations with the IDs 657 and 658. Your URL would look like this:

https://www.webconsultant247.com/?add_to_cart_m=656&var=657,568

When a user clicks on this link, the product with ID 656 and its variations 657 and 658 are added to the cart automatically. This way, your customers can directly add a product with specific variations to their cart, enhancing their shopping experience on your site.

You can find these numbers (product ID and variation IDs) from your WordPress dashboard in Products page, as earlier mentioned.

Variations and Product ID

Add to cart function needs the product ID and variation IDs

Product ID

Add to cart function needs the product ID

Remember, creating a seamless user experience can significantly impact your customer engagement and conversion rates. Happy URL crafting!

In Conclusion

Mastering this function allows you to harness the power of PHP, WordPress, and WooCommerce to develop an efficient, streamlined shopping experience for your customers. Remember, ensuring your website is SEO-friendly and user-friendly will pave the way for higher conversion rates and enhanced customer satisfaction. Be sure to adapt and test this function based on your theme’s unique characteristics and your specific needs. Happy coding!