WordPress has a built-in system for passing data through URLs using query variables. Here’s how to register custom query vars and use them in your templates — the WordPress way.
Register Custom Query Variables
WordPress maintains a whitelist of public query variables. To add your own, hook into the query_vars filter in your theme’s functions.php or a plugin:
add_filter( 'query_vars', function( $vars ) {
$vars[] = 'color';
$vars[] = 'size';
return $vars;
} );
Your custom variables are now recognized by WP_Query and won’t be stripped from URLs.
Build URLs with Query Args
Use add_query_arg() to build clean URLs with your custom variables:
$url = add_query_arg(
[
'color' => 'blue',
'size' => 'large',
],
home_url( '/shop/' )
);
// Result: https://example.com/shop/?color=blue&size=large
In a template:
<a href="<?php echo esc_url( add_query_arg( [ 'color' => 'blue' ], '/shop/' ) ); ?>">
Blue items
</a>
Retrieve the Values
On the destination page, use get_query_var() to read the values:
$color = get_query_var( 'color' );
$size = get_query_var( 'size' );
if ( $color ) {
echo 'Filtering by color: ' . esc_html( $color );
}
Things to Keep in Mind
- Always sanitize. Values from
get_query_var()come from user input — escape and validate before using them. - Avoid reserved names. Don’t use names that conflict with WordPress built-in query vars like
name,p,page,s, etc. Check the WP_Query docs for the full list. - Works with pretty permalinks. You can combine this with
add_rewrite_rule()to turn?color=blueinto/shop/color/blue/— but that’s a topic for another post.
Leave a comment