Track Custom Referrals Using Cookies with WP_Http_Cookie

Last updated 1 month ago

PHP
function set_referral_cookie() {
    if (isset($_GET['referral']) && !isset($_COOKIE['user_referral'])) {
        $referral_code = sanitize_text_field($_GET['referral']);
        $cookie = new WP_Http_Cookie(array(
            'name'     => 'user_referral',
            'value'    => $referral_code,
            'expires'  => time() + WEEK_IN_SECONDS,
            'path'     => '/',
        ));

        // Set the referral cookie for tracking.
        wp_remote_get(home_url(), array('cookies' => array($cookie)));
    }
}

add_action('init', 'set_referral_cookie');

function get_user_referral() {
    return isset($_COOKIE['user_referral']) ? sanitize_text_field($_COOKIE['user_referral']) : false;
}

// Example usage: Display referral code in the footer.
add_action('wp_footer', function () {
    if ($referral = get_user_referral()) {
        echo "<p>Your referral code: {$referral}</p>";
    }
});

All code snippets are licensed GPLv2 or later unless otherwise stated.