Apply WooCommerce Coupon From URL
🔑 ID:
👨💻
🕒
Description:
This custom WordPress snippet enhances the shopping experience on WooCommerce-based websites by allowing users to add a product to their cart and apply a discount coupon through a URL without the need for third-party plugins.
How the Snippet Works:
- Action Hook: It hooks into WordPress’s
init
action, which means it gets executed early when WordPress initializes. - Checking Parameters: It checks if the required URL parameters are present. If either parameter is missing, the function exits early.
- Product Addition: If the product ID is valid and the product is not already in the cart, it adds the product to the cart.
- Coupon Application: If a coupon code is provided and it hasn’t already been applied, the snippet applies the coupon to the cart.
- Redirection: After adding the product and applying the coupon, the user is redirected to the cart page to view their updated cart.
Usage Example:
To use this functionality, a URL needs to be constructed with specific parameters for the product ID and the coupon code. Here is how you can create such a URL:
- Base URL:
http://yourwebsite.com/
- Product ID Parameter:
custom-product-to-cart
(you can rename this) - Coupon Code Parameter:
custom-coupon
(you can rename this)
Example URL:
http://yourwebsite.com/?custom-product-to-cart=123&custom-coupon=SAVE20
In this example, 123
is the product ID and SAVE20
is the coupon code. When a user visits this URL, the product with the ID 123
will be added to their cart, and the coupon SAVE20
will be applied if applicable.
Customization:
You can easily customize the names of the parameters (custom-product-to-cart
and custom-coupon
) in the URL by editing their instances in the snippet. Just ensure that you replace them consistently throughout the code to match your custom parameter names.
This snippet provides a straightforward way to streamline promotions and improve user experience by simplifying the process of adding products and applying coupons with just a URL click.
Code:
![](https://learnwithhasan.com/wp-content/uploads/2023/12/Copy-of-Untitled-Design-1-1-150x150.png)
This section is only accessible to Power Members. Please upgrade your account to access this feature.
If you’re encountering any problems or need further assistance with this code, we’re here to help! Join our community on the forum or Discord for support, tips, and discussion.