Implementing a referral system involves multiple steps, and the details can vary based on your specific requirements and the structure of your WordPress theme. Below is a basic guide on how you might approach adding a "Refer a Friend" feature to your WordPress site with WooCommerce using PHP. This is a simplified example, and you may need to adjust it based on your specific needs and the structure of your theme.
1. Identify the Thank You Page
First, find the thank you page template in your WordPress theme. This is the page that users see after completing a purchase. It might be named thankyou.php or similar.
2. Modify the Thank You Page
Edit the thank you page template and add the referral message. You can use the wc_get_order function to get information about the order. Add the referral link with a unique identifier to the thank you page.
PHP:
// Inside your thank you page template
$order_id = get_query_var('order-received');
$order = wc_get_order($order_id);
if ($order) {
$referral_link = add_query_arg('referrer', get_current_user_id(), home_url());
echo '<p>Refer a friend and get rewards! Share this link: <a href="' . esc_url($referral_link) . '">' . esc_url($referral_link) . '</a></p>';
}
3. Create a Coupon for Referrers
In your WordPress admin panel, create a new coupon under WooCommerce → Coupons. Set up the coupon as you like (e.g., a percentage or fixed discount). Remember the coupon code, as you'll use it to apply discounts to referrers' orders.
4. Implement Referral Tracking
In your theme's functions.php file, add the following code to track referrals. This code checks if there's a referrer parameter in the URL and applies the coupon to the referrer's account.
PHP:
// Inside your theme's functions.php
add_action('woocommerce_thankyou', 'apply_referral_coupon');
function apply_referral_coupon($order_id) {
$referrer_id = isset($_GET['referrer']) ? intval($_GET['referrer']) : 0;
if ($referrer_id > 0) {
// Apply the coupon to the referrer's account
$coupon_code = 'YOUR_COUPON_CODE'; // Replace with your actual coupon code
WC()->cart->add_discount($coupon_code);
}
}
Replace 'YOUR_COUPON_CODE' with the actual coupon code you created in step 3.
Important Notes:
- This is a basic example, and you might need to enhance it based on your specific needs.
- Ensure you thoroughly test the referral system in a staging environment before deploying it to a live site.
- Consider implementing security measures to prevent abuse, like limiting the number of times a coupon can be used.
Remember to backup your site before making any changes, and consider consulting with a developer if you're not comfortable making these modifications yourself.