Istiaq Nirab full stack + ai
← Writing
WooCommerce Mar 19, 2023

WooCommerce apply coupon via url

Apply woocommerce coupon via custom url

If you’re unfamiliar with Programming then you may checkout

Advance Coupons for Woocommerce plugin which can extends default WooCommerce coupon features.

The example url must be look like:

https://springdevs.com/?coupon_code=DiscountCode

At first You need to check url & find coupon code. Then you need to set code into session because of You can’t run WC()->cart->apply_coupon($coupon_code) on init hook for some valid reasons.

add_action('init', "set_coupon_url");

function set_coupon_url() {
   if (isset($_GET['coupon_code'])) {
      $coupon_code = esc_url($_GET['coupon_code']);
      WC()->session->set('coupon_code', $coupon_code);
   }
}

Now, Check coupon is valid or Already not inserted in cart and apply coupon.

add_action("woocommerce_add_to_cart", "apply_coupon_via_url");
add_action("woocommerce_before_cart", "apply_coupon_via_url");

function apply_coupon_via_url() {
   $coupons = WC()->cart->get_applied_coupons();
   $code = WC()->session->get('coupon_code');
   $coupon_id = wc_get_coupon_id_by_code($code);

   // if coupon is invalid then return;
   if ($coupon_id == 0) return;

   if (in_array($code, $coupons)) {
         WC()->session->__unset('coupon_code');
   } else {
         WC()->cart->apply_coupon($code);
         WC()->session->__unset('coupon_code');
   }
}

Thanks.

Discussion

Comments run on giscus, backed by GitHub Discussions — sign in with GitHub to reply.

More posts
LLM

Five steps from a business problem to an LLM that actually ships

Understand, prepare, select, customize, productionize. A working order of operations for picking a language model and getting it into production without burning a quarter.

2026-09-12
NLP

N-grams: the language model before language models

How N-grams turn text into countable sequences, how they predict the next word, and why counting eventually stopped being enough.

2026-09-11
Laravel

Setup vsCode for Laravel Development

The extensions and keyboard shortcuts that turn Visual Studio Code into a proper Laravel editor.

2023-09-22
ContactGMT+6

Have something that needs building, fixing, or finishing? Write one paragraph — that's usually enough.

open to new work
Local time--:--:--
Based inDhaka, BD
Experience6+ years