Skip to content

Instantly share code, notes, and snippets.

@jooray
Last active September 13, 2024 11:48
Show Gist options
  • Save jooray/4c032b3dd3839449742ea591cba9253d to your computer and use it in GitHub Desktop.
Save jooray/4c032b3dd3839449742ea591cba9253d to your computer and use it in GitHub Desktop.
Add product to WooCommerce cart & redirect to checkout via URL parameter
<?php
/**
* Add a direct-to-checkout functionality to WooCommerce.
*
*
* When user follows the link with productcheckout parameter, it
* clears the existing shopping cart and adds the specified product
* to the cart (with optional quantity). You can add multiple products
* separated by commas.
* Then it redirects the user directly to the WooCommerce checkout page.
* You can also add coupon with the optional coupon parameter
*
* To use this functionality, you would construct a URL like this:
* https://yourwebsite.com/?productcheckout=123&quantity=2
* Replace '123' with the actual WooCommerce product ID.
* The 'quantity' parameter is optional and defaults to 1 if not provided.
*
* Installation
* Save this script in your WordPress installation's
* wp-content/mu-plugins/product-checkout.php directory.
* Note that mu-plugins are always active, so you don't need to worry about
* plugin activation.
*/
<?php
// Exit if accessed directly
if (!defined('ABSPATH')) {
exit;
}
add_action('template_redirect', 'custom_add_to_cart_redirect', 1);
function custom_add_to_cart_redirect() {
// Check if the 'productcheckout' is present in the URL
if (isset($_GET['productcheckout'])) {
$product_ids = explode(',', sanitize_text_field($_GET['productcheckout']));
error_log('Custom redirect triggered for products: ' . implode(', ', $product_ids));
WC()->cart->empty_cart();
foreach ($product_ids as $product_id) {
$product_id = absint($product_id);
if ($product_id) {
WC()->cart->add_to_cart($product_id, isset($_GET['quantity']) ? absint($_GET['quantity']) : 1);
}
}
// Check if there is a coupon to apply
if (isset($_GET['coupon'])) {
$coupon_code = sanitize_text_field($_GET['coupon']);
WC()->cart->apply_coupon($coupon_code);
error_log('Coupon applied: ' . $coupon_code);
}
wp_safe_redirect(wc_get_checkout_url());
exit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment