Created
March 25, 2025 06:25
-
-
Save gonzalesc/d8894c7e42fc60e230d19712e43a4091 to your computer and use it in GitHub Desktop.
Add multiple products to cart in the URL in WooCommerce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_action( 'wp_loaded', 'maybeAddMultipleProductToCart', 25 ); | |
/** | |
* Add Multiple products by URL | |
* @example | |
* simple: http://wpplugins.local/cart/?add-to-cart=27,28 | |
* variation : http://wpplugins.local/cart/?add-to-cart=208,32 | |
* @return void | |
* @throws Exception | |
*/ | |
function maybeAddMultipleProductToCart(): void { | |
// Early return | |
if ( ! function_exists('WC') || empty( $_REQUEST['add-to-cart'] ) || ! str_contains( $_REQUEST['add-to-cart'], ',' ) ) { | |
return; | |
} | |
$productIDs = array_filter( array_map( 'absint', explode( ',', $_REQUEST['add-to-cart'] ) ) ); | |
// Early return | |
if ( empty( $productIDs ) ) { | |
return; | |
} | |
$added = []; | |
foreach ( $productIDs as $productID ) { | |
$product = wc_get_product( $productID ); | |
if ( $product && $product->is_type( 'variable' ) ) { | |
wc_add_notice( | |
sprintf( | |
__( | |
'Please choose product options by visiting <a href="%1$s" title="%2$s">%2$s</a>.', | |
'woocommerce' | |
), | |
esc_url( get_permalink( $productID ) ), | |
esc_html( $product->get_name() ) ), | |
'error' | |
); | |
continue; | |
} | |
if ( false !== WC()->cart->add_to_cart( $productID ) ) { | |
$added[ $productID ] = 1; | |
} | |
} | |
if ( ! empty( $added ) ) { | |
wc_add_to_cart_message( $added, true ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment