Let WordPress recognise your own URL parameter, like ?ref=partner, and read it safely anywhere with get_query_var().
add_filter( 'query_vars', function ( array $vars ): array {
$vars[] = 'ref';
return $vars;
} );
// Example: remember a referral code for 30 days.
add_action( 'template_redirect', function (): void {
$ref = sanitize_key( get_query_var( 'ref' ) );
if ( '' === $ref || headers_sent() ) {
return;
}
setcookie( 'nahnu_ref', $ref, [
'expires' => time() + 30 * DAY_IN_SECONDS,
'path' => COOKIEPATH ?: '/',
'domain' => COOKIE_DOMAIN,
'secure' => is_ssl(),
'httponly' => true,
'samesite' => 'Lax',
] );
} );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
WordPress ignores URL parameters it doesn’t know about, and reading $_GET directly skips its normal handling. Registering a query variable lets you use it with get_query_var(), in rewrite rules and in pre_get_posts.
The query_vars filter adds ref to the list of public query variables WordPress reads from the URL. After that, get_query_var( 'ref' ) returns its value.
The example saves the value in a cookie for 30 days, cleaned with sanitize_key() and set as HTTP-only and SameSite=Lax, so you can credit a referral when the visitor buys later.
p, name, s or page.?ref= may need to bypass the cache for the cookie to be set.Visit yoursite.com/?ref=test and check your browser’s cookies. nahnu_ref should be set to test.