Add the code below to functions.php
Once that’s done, WooCommerce add-to-cart links will work with multiple products in the following format:
https://website.com/cart/?add-to-cart=586,592,593,595,596&quantities=1,1,1,1,1
586, etc. are the product ID’s you want to add to cart, and in this link, the 1’s are the quantity of each product, listed in order, separated by commas.
/**
* Add multiple variable products to the cart using URL parameters.
*
*
* The function expects two URL parameters:
* – ‘add-to-cart’: a comma-separated list of product IDs to add to the cart.
* – ‘quantities’: a comma-separated list of quantities corresponding to each product ID.
*
* The function adds each product to the cart with the corresponding quantity.
* If the number of product IDs and quantities do not match, the function does nothing.
*/
function add_multiple_products_to_cart() {
// Check if ‘add-to-cart’ and ‘quantities’ parameters are present in the URL.
if ( isset( $_GET[‘add-to-cart’] ) && isset( $_GET[‘quantities’] ) ) {
// Split the ‘add-to-cart’ and ‘quantities’ parameters into arrays.
$product_ids = explode( ‘,’, $_GET[‘add-to-cart’] );
$quantities = explode( ‘,’, $_GET[‘quantities’] );
// Check if the count of product IDs matches the count of quantities.
if ( count( $product_ids ) == count( $quantities ) ) {
// Loop over the arrays and for each pair of product ID and quantity, add the product to the cart.
for ( $i = 0; $i < count( $product_ids ); $i++ ) {
$product_id = $product_ids[$i];
$quantity = $quantities[$i];
// Add the product to the cart using the WooCommerce function.
WC()->cart->add_to_cart( $product_id, $quantity );
}
}
}
}
// Attach our function to the ‘init’ action hook.
add_action( ‘init’, ‘add_multiple_products_to_cart’ );
