Table of Contents
Key Takeaways
Creating the Coupon Codes
Creating the WooCommerce Redeem Products Page
Building the Ajax Functionality
Register Our Ajax Handler
Handling the Coupon Logic
Handling the Form Submission with jQuery
Final Result
Empty Field Error Message
Invalid Code Error Message
Valid Code/Cart Populated
Conclusion
Frequently Asked Questions (FAQs) on Creating a WooCommerce Redeem Coupon Page
How Can I Create a Unique Coupon Code in WooCommerce?
Can I Set an Expiry Date for My WooCommerce Coupon?
How Can I Limit the Usage of My WooCommerce Coupon?
Can I Apply a Coupon to Specific Products or Categories?
How Can I Enable Customers to Apply Coupons Automatically?
Can I Create a Coupon That Gives a Free Gift?
How Can I Share My WooCommerce Coupon with Customers?
Can I Track the Usage of My WooCommerce Coupon?
Can I Create a Coupon That Applies to Shipping Costs?
Can I Restrict a Coupon to New Customers Only?
Home CMS Tutorial WordPress Creating a WooCommerce Redeem Products Page

Creating a WooCommerce Redeem Products Page

Feb 18, 2025 pm 12:56 PM

Creating a WooCommerce Redeem Products Page

Key Takeaways

  • WooCommerce allows you to create unique coupon codes that customers can redeem for products, which can be particularly useful for pre-selling items at events such as conferences.
  • A WooCommerce Redeem Products Page can be created by duplicating your page.php and transforming it into a page template, such as page-coupon-redeem.php. This page will feature a simple form where customers can enter their coupon code.
  • The redemption process can be enhanced with Ajax functionality, which allows for smoother and faster user interactions by reducing the need for page loads. This is achieved by validating the coupon code and automatically adding the corresponding products to the cart for checkout.
  • The Smart Coupons plugin can be used to generate multiple coupons, track usage, limit usage, set expiry dates, apply coupons to specific products or categories, and enable automatic application of coupons.

In this article, we will explore a unique way of allowing your customers to easily redeem a product or group of products they may have paid for already perhaps at a conference or other similar event.

Let’s talk a bit more about the concept. Say you are a store owner with a revolutionary new product and you present it to thousands of people at a conference. At the end of your speech, those customers willing to try your product can do so and pay for it ahead of time. You may even have enticed them by lowering your price to the first 500 customers.

In this scenario, what you’ll do in WooCommerce is create 500 coupons, with a product discount of 100%. You could use the Smart Coupons plugin to generate these 500 coupons so that you don’t have to create them manually. Each customer who paid in advance gets a coupon code but as far as the customer knows it is just a code to redeem the products.

Creating the Coupon Codes

If you are serious enough about your offer, then you will try to make the coupon codes look random and make it hard, if not impossible for users to come up with a valid coupon code. Make sure you select which products are tied to this coupon so we can add them to the cart automatically later on. Take a look at one of the coupons I created, pay close attention to the settings:

Creating a WooCommerce Redeem Products Page

Creating the WooCommerce Redeem Products Page

You can easily make a copy of your page.php and turn it into a page template so you can use it for the page we are going to be sending those customers so they can redeem their products. Name it something like page-coupon-redeem.php

The following markup is what we’ll use to format the form displayed to the customer on that page. It is just a form with two fields, one for entering their code and the actual submit button. We are trying to keep this as simple as possible for the customer; so we are going to do everything via Ajax so there are as little page loads as possible.

<span><span><span><div</span> class<span>="redeem-coupon"</span>></span>
</span>	<span><span><span><form</span> id<span>="ajax-coupon-redeem"</span>></span>
</span>		<span><span><span><p</span>></span>
</span>			<span><span><span><input</span> type<span>="text"</span> name<span>="coupon"</span> id<span>="coupon"</span>/></span>
</span>			<span><span><span><input</span> type<span>="submit"</span> name<span>="redeem-coupon"</span> value<span>="Redeem Offer"</span> /></span>
</span>		<span><span><span></p</span>></span>
</span>		<span><span><span><p</span> class<span>="result"</span>></span><span><span></p</span>></span>
</span>	<span><span><span></form</span>></span><!-- #ajax-coupon-redeem -->
</span><span><span><span></div</span>></span><!-- .redeem-coupon --></span>
Copy after login

When the user enters a code and hits the submit button, the value entered in the text field is sent for validation and if it happens to be valid, then the user will be redirected to the ‘Cart’ page and the products will already be there to checkout for the price of $0. If by any chance the code is incorrect, then we notify the user that something is wrong and the code entered is not valid.

Building the Ajax Functionality

If you have never done Ajax in WordPress, please refer to my previous article Adding Ajax to Your WordPress Plugin for a brief introduction to how Ajax is performed in WordPress.

Let’s begin building the Ajax functionality required for our ‘Redeem Your Products Page’ to function as expected. All the code that follows goes in your functions.php file of your theme.

Register Our Ajax Handler

First register our Ajax call handler by hooking into the wp_ajax_$action and wp_ajax_nopriv_$action actions.

<span>add_action( 'wp_ajax_spyr_coupon_redeem_handler', 'spyr_coupon_redeem_handler' );
</span><span>add_action( 'wp_ajax_nopriv_spyr_coupon_redeem_handler', 'spyr_coupon_redeem_handler' );</span>
Copy after login

Note that the same function is handling the Ajax call for both customers whether they are logged in or not.

Next, we are going to start building our logic to account for the following possible scenarios:

  • Code text field being empty
  • Code being invalid, meaning is not a valid coupon code
  • Successfully presenting a valid coupon

Handling the Coupon Logic

Now that we have our actions registered and we know what to do, we need to write the actual function which will handle our possible scenarios.

<span><span><?php
</span></span><span><span>function spyr_coupon_redeem_handler() {
</span></span><span>
</span><span>	<span>// Get the value of the coupon code
</span></span><span>	<span>$code = $_REQUEST['coupon_code'];
</span></span><span>
</span><span>	<span>// Check coupon code to make sure is not empty
</span></span><span>	<span>if( empty( $code ) || !isset( $code ) ) {
</span></span><span>		<span>// Build our response
</span></span><span>		<span>$response = array(
</span></span><span>			<span>'result'    => 'error',
</span></span><span>			<span>'message'   => 'Code text field can not be empty.'
</span></span><span>		<span>);
</span></span><span>
</span><span>		<span>header( 'Content-Type: application/json' );
</span></span><span>		<span>echo json_encode( $response );
</span></span><span>
</span><span>		<span>// Always exit when doing ajax
</span></span><span>		<span>exit();
</span></span><span>	<span>}
</span></span><span>
</span><span>	<span>// Create an instance of WC_Coupon with our code
</span></span><span>	<span>$coupon = new WC_Coupon( $code );
</span></span><span>
</span><span>	<span>// Check coupon to make determine if its valid or not
</span></span><span>	<span>if( ! $coupon->id && ! isset( $coupon->id ) ) {
</span></span><span>		<span>// Build our response
</span></span><span>		<span>$response = array(
</span></span><span>			<span>'result'    => 'error',
</span></span><span>			<span>'message'   => 'Invalid code entered. Please try again.'
</span></span><span>		<span>);
</span></span><span>
</span><span>		<span>header( 'Content-Type: application/json' );
</span></span><span>		<span>echo json_encode( $response );
</span></span><span>
</span><span>		<span>// Always exit when doing ajax
</span></span><span>		<span>exit();
</span></span><span>
</span><span>	<span>} else {
</span></span><span>		<span>// Coupon must be valid so we must
</span></span><span>		<span>// populate the cart with the attached products
</span></span><span>		<span>foreach( $coupon->product_ids as $prod_id ) {
</span></span><span>			<span>WC()->cart->add_to_cart( $prod_id );
</span></span><span>		<span>}
</span></span><span>
</span><span>		<span>// Build our response
</span></span><span>		<span>$response = array(
</span></span><span>			<span>'result'    => 'success',
</span></span><span>			<span>'href'      => WC()->cart->get_cart_url()
</span></span><span>		<span>);
</span></span><span>
</span><span>		<span>header( 'Content-Type: application/json' );
</span></span><span>		<span>echo json_encode( $response );
</span></span><span>
</span><span>		<span>// Always exit when doing ajax
</span></span><span>		<span>exit();
</span></span><span>	<span>}
</span></span><span><span>}</span></span>
Copy after login

Handling the Form Submission with jQuery

All that’s left to do now is build the jQuery code to submit the coupon code to WordPress for processing and handling the JSON data returned.

<span>jQuery( document ).ready( function() {
</span>       <span>jQuery( '#ajax-coupon-redeem input[type="submit"]').click( function( ev ) {
</span>
        <span>// Get the coupon code
</span>        <span>var code = jQuery( 'input#coupon').val();
</span>
        <span>// We are going to send this for processing
</span>        data <span>= {
</span>            <span>action: 'spyr_coupon_redeem_handler',
</span>            <span>coupon_code: code
</span>        <span>}
</span>
        <span>// Send it over to WordPress.
</span>        jQuery<span>.post( woocommerce_params.ajax_url, data, function( returned_data ) {
</span>            <span>if( returned_data.result == 'error' ) {
</span>                <span>jQuery( 'p.result' ).html( returned_data.message );
</span>            <span>} else {
</span>                <span>// Hijack the browser and redirect user to cart page
</span>                <span>window.location.href = returned_data.href;
</span>            <span>}
</span>        <span>})
</span>
        <span>// Prevent the form from submitting
</span>        ev<span>.preventDefault();
</span>    <span>}); 
</span><span>});</span>
Copy after login

Final Result

The styling of the form is entirely up to you. I’ve used the default Twenty Twelve theme and WooCommerce’s dummy data and with a few CSS rules this is what I’ve got below.

Empty Field Error Message
Creating a WooCommerce Redeem Products Page
Invalid Code Error Message
Creating a WooCommerce Redeem Products Page
Valid Code/Cart Populated
Creating a WooCommerce Redeem Products Page

Conclusion

Even though this scenario might not apply to every store out there, WooCommerce shines in providing us with a set of tools through their API so that we can accomplish almost anything we set our minds to. Add WordPress to the mix and you’ve got a complete eCommerce solution which is second to none.

It is my hope that through this article, I’ve provided some insight of how coupons work in WooCommerce and that you’ll feel more comfortable in using it on your next project.

Frequently Asked Questions (FAQs) on Creating a WooCommerce Redeem Coupon Page

How Can I Create a Unique Coupon Code in WooCommerce?

Creating a unique coupon code in WooCommerce is a straightforward process. First, navigate to the WooCommerce section of your WordPress dashboard. Click on ‘Coupons’ under the ‘Marketing’ tab. Click on ‘Add Coupon’ and you’ll be directed to a new page where you can create your unique coupon code. You can customize the coupon code, discount type, coupon amount, and other settings according to your needs. Remember to click ‘Publish’ to save your new coupon code.

Can I Set an Expiry Date for My WooCommerce Coupon?

Yes, you can set an expiry date for your WooCommerce coupon. When creating or editing a coupon, you’ll find an ‘Coupon expiry date’ option under the ‘General’ tab. Here, you can select the date you want the coupon to expire. After setting the date, remember to click ‘Publish’ or ‘Update’ to save your changes.

How Can I Limit the Usage of My WooCommerce Coupon?

WooCommerce allows you to limit the usage of your coupons. Under the ‘Usage limit’ tab when creating or editing a coupon, you can set a limit on the number of times the coupon can be used, the number of items it can apply to, or the number of times a single user can use the coupon. After setting the limits, remember to click ‘Publish’ or ‘Update’ to save your changes.

Can I Apply a Coupon to Specific Products or Categories?

Yes, WooCommerce allows you to apply coupons to specific products or categories. Under the ‘Usage restriction’ tab when creating or editing a coupon, you can select specific products or categories that the coupon will apply to. You can also exclude certain products or categories from the coupon’s discount. After setting the restrictions, remember to click ‘Publish’ or ‘Update’ to save your changes.

How Can I Enable Customers to Apply Coupons Automatically?

To enable customers to apply coupons automatically, you’ll need to use a plugin like ‘Smart Coupons for WooCommerce’. Once installed and activated, navigate to the plugin’s settings. Here, you can enable the ‘Auto Apply’ option, which will automatically apply the coupon’s discount when the customer’s cart meets the coupon’s conditions.

Can I Create a Coupon That Gives a Free Gift?

Yes, you can create a coupon that gives a free gift. You’ll need to use a plugin like ‘Smart Coupons for WooCommerce’. Once installed and activated, navigate to the plugin’s settings. Here, you can create a new coupon and set the discount type to ‘Free Gift’. You can then select the product that will be given as a free gift when the coupon is used.

How Can I Share My WooCommerce Coupon with Customers?

There are several ways to share your WooCommerce coupon with customers. You can include the coupon code in your marketing emails, display it on your website, or share it on social media. You can also use a plugin like ‘Smart Coupons for WooCommerce’ to send the coupon directly to customers via email.

Can I Track the Usage of My WooCommerce Coupon?

Yes, you can track the usage of your WooCommerce coupon. Under the ‘Reports’ section of your WooCommerce dashboard, you can view detailed reports on the usage of your coupons. You can see how many times each coupon has been used, the total discount amount given, and more.

Can I Create a Coupon That Applies to Shipping Costs?

Yes, you can create a coupon that applies to shipping costs. When creating or editing a coupon, under the ‘Discount type’ dropdown, select ‘Shipping discount’. You can then set the discount amount. Remember to click ‘Publish’ or ‘Update’ to save your changes.

Can I Restrict a Coupon to New Customers Only?

Yes, you can restrict a coupon to new customers only. Under the ‘Usage restriction’ tab when creating or editing a coupon, you can check the box that says ‘Allow new customers only’. This will ensure that only customers who are making their first purchase can use the coupon. After setting the restriction, remember to click ‘Publish’ or ‘Update’ to save your changes.

The above is the detailed content of Creating a WooCommerce Redeem Products Page. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to Embed and Protect PDF Files With a WordPress Plugin How to Embed and Protect PDF Files With a WordPress Plugin Mar 09, 2025 am 11:08 AM

This guide demonstrates how to embed and protect PDF files within WordPress posts and pages using a WordPress PDF plugin. PDFs offer a user-friendly, universally accessible format for various content, from catalogs to presentations. This method ens

Is WordPress easy for beginners? Is WordPress easy for beginners? Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

Why would anyone use WordPress? Why would anyone use WordPress? Apr 02, 2025 pm 02:57 PM

People choose to use WordPress because of its power and flexibility. 1) WordPress is an open source CMS with strong ease of use and scalability, suitable for various website needs. 2) It has rich themes and plugins, a huge ecosystem and strong community support. 3) The working principle of WordPress is based on themes, plug-ins and core functions, and uses PHP and MySQL to process data, and supports performance optimization.

Is WordPress still free? Is WordPress still free? Apr 04, 2025 am 12:06 AM

The core version of WordPress is free, but other fees may be incurred during use. 1. Domain names and hosting services require payment. 2. Advanced themes and plug-ins may be charged. 3. Professional services and advanced features may be charged.

How much does WordPress cost? How much does WordPress cost? Apr 05, 2025 am 12:13 AM

WordPress itself is free, but it costs extra to use: 1. WordPress.com offers a package ranging from free to paid, with prices ranging from a few dollars per month to dozens of dollars; 2. WordPress.org requires purchasing a domain name (10-20 US dollars per year) and hosting services (5-50 US dollars per month); 3. Most plug-ins and themes are free, and the paid price ranges from tens to hundreds of dollars; by choosing the right hosting service, using plug-ins and themes reasonably, and regularly maintaining and optimizing, the cost of WordPress can be effectively controlled and optimized.

Should I use Wix or WordPress? Should I use Wix or WordPress? Apr 06, 2025 am 12:11 AM

Wix is ​​suitable for users who have no programming experience, and WordPress is suitable for users who want more control and expansion capabilities. 1) Wix provides drag-and-drop editors and rich templates, making it easy to quickly build a website. 2) As an open source CMS, WordPress has a huge community and plug-in ecosystem, supporting in-depth customization and expansion.

What is the WordPress good for? What is the WordPress good for? Apr 07, 2025 am 12:06 AM

WordPressisgoodforvirtuallyanywebprojectduetoitsversatilityasaCMS.Itexcelsin:1)user-friendliness,allowingeasywebsitesetup;2)flexibilityandcustomizationwithnumerousthemesandplugins;3)SEOoptimization;and4)strongcommunitysupport,thoughusersmustmanageper

See all articles