Created
April 15, 2025 12:16
-
-
Save kidino/35a27d66b0f4857a8e6002adea6435da to your computer and use it in GitHub Desktop.
WooCommerce Add-to-Cart & Empty-Cart from URL
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 | |
// empties the shopping cart | |
add_action( 'wp_loaded', 'custom_woocommerce_empty_cart_action', 20 ); | |
function custom_woocommerce_empty_cart_action() { | |
if ( isset( $_GET['empty-cart'] ) && 'yes' === esc_html( $_GET['empty-cart'] ) ) { | |
WC()->cart->empty_cart(); | |
} | |
} | |
// add products to cart via the URL | |
add_action( 'wp_loaded', 'custom_woocommerce_add_multiple_to_cart_via_url', 25 ); | |
function custom_woocommerce_add_multiple_to_cart_via_url() { | |
if ( isset( $_GET['add-to-cart'] ) ) { | |
$products = explode( ',', sanitize_text_field( $_GET['add-to-cart'] ) ); | |
foreach ( $products as $product_data ) { | |
// Support formats like: 123 or 123:2 (product ID : quantity) | |
$parts = explode( ':', $product_data ); | |
$product_id = absint( $parts[0] ); | |
$quantity = isset( $parts[1] ) ? absint( $parts[1] ) : 1; | |
if ( $product_id > 0 && get_post_type( $product_id ) === 'product' ) { | |
WC()->cart->add_to_cart( $product_id, $quantity ); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment