Skip to content

PHP add_rewrite_var() Function: Everything You Need to Know

As a WordPress developer, you may need to register a custom query variable for use with rewrite rules. The add_rewrite_var() function is a WordPress API function that allows you to add a new query variable to the list of recognized rewrite query variables. In this article, we will take an in-depth look at the add_rewrite_var() function and its usage.

What is the add_rewrite_var() Function?

The add_rewrite_var() function is a WordPress function that registers a custom query variable. This makes the variable available for use in WordPress rewrite rules and query parsing.

How to Use the add_rewrite_var() Function

Using the add_rewrite_var() function is straightforward. It accepts a single parameter: the name of the query variable. Here is the syntax:

Syntax

php
add_rewrite_var( string $name ): void

Because WordPress loads functions early in the request lifecycle, you typically call this function inside a callback hooked to the init action. Here is a correct usage example:

Example

php
function my_custom_query_var() {
    add_rewrite_var( 'my_custom_var' );
}
add_action( 'init', 'my_custom_query_var' );

In this example, we register a new query variable named my_custom_var. Once registered, you can access its value in your theme or plugin using get_query_var( 'my_custom_var' ).

Conclusion

The add_rewrite_var() function is a useful WordPress tool for registering custom query variables for rewrite rules. By understanding its single-parameter syntax and proper hooking practice, you can easily extend WordPress query parsing. We hope this article has been informative and useful in understanding the add_rewrite_var() function.

Practice

What does the function add_rewrite_var() in PHP do?

Dual-run preview — compare with live Symfony routes.