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
Databases

ACID in practice: what SQLite, Postgres, MySQL and MariaDB actually promise

Atomicity, consistency, isolation and durability, one letter at a time, and how differently SQLite, Postgres, MySQL, MariaDB and a few others implement each one. Same words, different guarantees.

2026-10-01
Networking

TCP: how a connection actually works

What TCP does on top of IP: ports, the three-way handshake, sequence numbers, ACKs, retransmission, closing a connection, and the costs that pushed HTTP/3 onto QUIC.

2026-09-26
NLP

Vectorizing text: from word counts to meaning

How text becomes numbers a model can work with: one-hot vectors, bag of words, TF-IDF, the hashing trick, word embeddings and sentence embeddings, and when to use each.

2026-09-25
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