To create a “Click to Download Coupon Code” feature on a WooCommerce page, you need to set up a few things:
- Create a WooCommerce coupon.
- Create a custom shortcode to display the coupon code and download link.
- Track the download (optional, but recommended for better management).
Here’s a step-by-step guide:
Step 1: Create a WooCommerce Coupon
- Go to WooCommerce > Coupons in your WordPress dashboard.
- Click “Add Coupon”.
- Enter a Coupon Code and set the details (e.g., discount type, amount, usage restrictions).
- Publish the Coupon.
Step 2: Create a Custom Shortcode
You’ll need to add a custom function to your theme’s functions.php
file to create a shortcode that displays the coupon code and provides a download link.
- Edit Your Theme’s Functions.php File:
- Navigate to Appearance > Theme Editor.
- Select the
functions.php
file from the right sidebar.
- Add the Custom Shortcode Function:
- Add the following code to your
functions.php
file:
- Add the following code to your
phpCopy code// Function to create a download link for the coupon code
function download_coupon_code_shortcode($atts) {
// Attributes for the shortcode
$atts = shortcode_atts(
array(
'code' => '', // The coupon code
),
$atts,
'download_coupon'
);
// If no coupon code is provided, return a message
if (empty($atts['code'])) {
return '<p>No coupon code provided.</p>';
}
// Create the download link
$download_link = '<a href="#" id="download-coupon" data-coupon="' . esc_attr($atts['code']) . '">Click here to download your coupon code</a>';
// Return the download link
return $download_link;
}
add_shortcode('download_coupon', 'download_coupon_code_shortcode');
// Enqueue the script
function enqueue_download_coupon_script() {
wp_enqueue_script('download-coupon-script', get_template_directory_uri() . '/js/download-coupon.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_download_coupon_script');
Step 3: Create the JavaScript for Downloading the Coupon
You need to create a JavaScript file that handles the download when the link is clicked.
- Create a JavaScript File:
- In your theme’s directory, create a new folder called
js
if it doesn’t exist. - In the
js
folder, create a file calleddownload-coupon.js
.
- In your theme’s directory, create a new folder called
- Add the Following JavaScript Code:
javascriptCopy codejQuery(document).ready(function($) {
$('#download-coupon').on('click', function(e) {
e.preventDefault();
var couponCode = $(this).data('coupon');
// Create a temporary element to initiate the download
var $tempElement = $('<a>');
$tempElement.attr('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(couponCode));
$tempElement.attr('download', 'coupon-code.txt');
// Append the element to the body and trigger the download
$('body').append($tempElement);
$tempElement[0].click();
// Remove the temporary element
$tempElement.remove();
});
});
Step 4: Use the Shortcode on a Page
- Create or Edit a Page:
- Go to Pages > Add New or edit an existing page where you want to display the download link.
- Insert the Shortcode:
- In the content editor, insert the
[download_coupon code="YOUR_COUPON_CODE"]
shortcode, replacingYOUR_COUPON_CODE
with your actual coupon code.
- In the content editor, insert the
Step 5: Test the Feature
- Visit the Page:
- Navigate to the page where you inserted the shortcode.
- Click the download link to ensure the coupon code is downloaded as a text file.
Optional: Tracking the Downloads
If you want to track how many times the coupon code is downloaded, you can modify the JavaScript to send an AJAX request to a WordPress endpoint that logs the download. Here’s a brief outline of how to do that:
- Add AJAX Endpoint in PHP:
phpCopy code// Function to handle the AJAX request
function log_coupon_download() {
if ( isset($_POST['coupon_code']) ) {
// Log the download (you can implement your logging logic here)
// For example, increment a counter in the database or write to a log file
$coupon_code = sanitize_text_field($_POST['coupon_code']);
// Example: Update a custom field (meta data) for the coupon
$current_count = get_option('coupon_download_count_' . $coupon_code, 0);
update_option('coupon_download_count_' . $coupon_code, $current_count + 1);
wp_send_json_success('Coupon download logged.');
}
wp_send_json_error('Invalid request.');
}
add_action('wp_ajax_log_coupon_download', 'log_coupon_download');
add_action('wp_ajax_nopriv_log_coupon_download', 'log_coupon_download');
- Update JavaScript to Send AJAX Request:
javascriptCopy codejQuery(document).ready(function($) {
$('#download-coupon').on('click', function(e) {
e.preventDefault();
var couponCode = $(this).data('coupon');
// Log the download via AJAX
$.post(
ajaxurl,
{
action: 'log_coupon_download',
coupon_code: couponCode
},
function(response) {
if (response.success) {
console.log(response.data);
} else {
console.error(response.data);
}
}
);
// Create a temporary element to initiate the download
var $tempElement = $('<a>');
$tempElement.attr('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(couponCode));
$tempElement.attr('download', 'coupon-code.txt');
// Append the element to the body and trigger the download
$('body').append($tempElement);
$tempElement[0].click();
// Remove the temporary element
$tempElement.remove();
});
});
By following these steps, you can create a feature on your WooCommerce site that allows users to click and download a coupon code, and optionally track how many times the coupon is downloaded.
To create a "Click to Download Coupon Code" feature that only allows logged-in users to download and limits the number of downloads to 10 users on a WooCommerce page, you can follow these steps. This involves modifying the previous steps to include user authentication checks and a download limit.
Step 1: Create a WooCommerce Coupon
Go to WooCommerce > Coupons in your WordPress dashboard.
Click "Add Coupon".
Enter a Coupon Code and set the details (e.g., discount type, amount, usage restrictions).
Publish the Coupon.
Step 2: Create a Custom Shortcode with Download Limits
Edit Your Theme's Functions.php File:
Navigate to Appearance > Theme Editor.
Select the functions.php file from the right sidebar.
Add the Custom Shortcode Function:
Add the following code to your functions.php file:
php
Copy code
// Function to create a download link for the coupon code
function download_coupon_code_shortcode($atts) {
// Attributes for the shortcode
$atts = shortcode_atts(
array(
'code' => '', // The coupon code
),
$atts,
'download_coupon'
);
// If no coupon code is provided, return a message
if (empty($atts['code'])) {
return '<p>No coupon code provided.</p>';
}
// Check if the user is logged in
if (!is_user_logged_in()) {
return '<p>Please log in to download the coupon code.</p>';
}
// Get current user info
$current_user = wp_get_current_user();
// Get the download count option
$download_count = get_option('coupon_download_count_' . $atts['code'], 0);
// Check if the download limit has been reached
if ($download_count >= 10) {
return '<p>Sorry, the download limit for this coupon code has been reached.</p>';
}
// Create the download link
$download_link = '<a href="#" id="download-coupon" data-coupon="' . esc_attr($atts['code']) . '">Click here to download your coupon code</a>';
// Return the download link
return $download_link;
}
add_shortcode('download_coupon', 'download_coupon_code_shortcode');
// Enqueue the script
function enqueue_download_coupon_script() {
wp_enqueue_script('download-coupon-script', get_template_directory_uri() . '/js/download-coupon.js', array('jquery'), null, true);
wp_localize_script('download-coupon-script', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'enqueue_download_coupon_script');
// Function to handle the AJAX request
function log_coupon_download() {
if ( isset($_POST['coupon_code']) ) {
// Log the download (you can implement your logging logic here)
// For example, increment a counter in the database or write to a log file
$coupon_code = sanitize_text_field($_POST['coupon_code']);
$current_user = wp_get_current_user();
// Check if the user is logged in
if (!is_user_logged_in()) {
wp_send_json_error('You must be logged in to download the coupon.');
}
// Get the download count option
$download_count = get_option('coupon_download_count_' . $coupon_code, 0);
// Check if the download limit has been reached
if ($download_count >= 10) {
wp_send_json_error('The download limit has been reached.');
}
// Increment the download count
update_option('coupon_download_count_' . $coupon_code, $download_count + 1);
wp_send_json_success('Coupon download logged.');
}
wp_send_json_error('Invalid request.');
}
add_action('wp_ajax_log_coupon_download', 'log_coupon_download');
add_action('wp_ajax_nopriv_log_coupon_download', 'log_coupon_download');
Step 3: Create the JavaScript for Downloading the Coupon
Create a JavaScript File:
In your theme's directory, create a new folder called js if it doesn't exist.
In the js folder, create a file called download-coupon.js.
Add the Following JavaScript Code:
javascript
Copy code
jQuery(document).ready(function($) {
$('#download-coupon').on('click', function(e) {
e.preventDefault();
var couponCode = $(this).data('coupon');
// Log the download via AJAX
$.post(
ajax_object.ajax_url,
{
action: 'log_coupon_download',
coupon_code: couponCode
},
function(response) {
if (response.success) {
// Create a temporary element to initiate the download
var $tempElement = $('<a>');
$tempElement.attr('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(couponCode));
$tempElement.attr('download', 'coupon-code.txt');
// Append the element to the body and trigger the download
$('body').append($tempElement);
$tempElement[0].click();
// Remove the temporary element
$tempElement.remove();
} else {
alert(response.data);
}
}
);
});
});
Step 4: Use the Shortcode on a Page
Create or Edit a Page:
Go to Pages > Add New or edit an existing page where you want to display the download link.
Insert the Shortcode:
In the content editor, insert the [download_coupon code="YOUR_COUPON_CODE"] shortcode, replacing YOUR_COUPON_CODE with your actual coupon code.
Step 5: Test the Feature
Visit the Page:
Log in to your WooCommerce site as a user.
Navigate to the page where you inserted the shortcode.
Click the download link to ensure the coupon code is downloaded as a text file.
Ensure the download count is correctly incremented and the limit is enforced.
By following these steps, you create a "Click to Download Coupon Code" feature on your WooCommerce site that only allows logged-in users to download the coupon code and limits the number of downloads to 10 users. This approach leverages WordPress hooks, AJAX, and shortcodes to provide a flexible and secure solution.