REST API & Developer PHP Intermediate

Register and Use a Custom Query Variable

Let WordPress recognise your own URL parameter, like ?ref=partner, and read it safely anywhere with get_query_var().

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 21 lines
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',
	] );
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

How it works

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.

Things to watch

  • Choose names that won’t clash with WordPress’s own, like p, name, s or page.
  • Setting a cookie can count as tracking under privacy laws. Mention it in your cookie policy.
  • If you use page caching, pages with ?ref= may need to bypass the cache for the cookie to be set.

How to test it

Visit yoursite.com/?ref=test and check your browser’s cookies. nahnu_ref should be set to test.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only