Using WordPress ‘query_vars’ PHP filter

The ‘query_vars’ filter enables you to modify the list of allowed query variables before processing them in WordPress.

This filter is essential for allowing custom rewrite rules with your own arguments or other custom query variables that you want to be publicly available.

Usage

To use the filter, create a function that modifies the $public_query_vars array and then use add_filter() to apply your function to the ‘query_vars’ filter.

function your_function_name( $public_query_vars ) {
    // Your code to modify $public_query_vars
    return $public_query_vars;
}
add_filter( 'query_vars', 'your_function_name' );

Parameters

  • $public_query_vars (string[]): The array of allowed query variable names.

Examples

Adding a Custom Query Variable

function add_custom_query_var( $public_query_vars ) {
    $public_query_vars[] = 'custom_query_var';
    return $public_query_vars;
}
add_filter( 'query_vars', 'add_custom_query_var' );

This example adds a new query variable called ‘custom_query_var’ to the list of allowed query variables.

Removing a Query Variable

function remove_query_var( $public_query_vars ) {
    $key = array_search( 'custom_query_var', $public_query_vars );
    if ( false !== $key ) {
        unset( $public_query_vars[$key] );
    }
    return $public_query_vars;
}
add_filter( 'query_vars', 'remove_query_var' );

In this example, we remove the ‘custom_query_var’ from the list of allowed query variables.

Modifying an Existing Query Variable

function modify_query_var( $public_query_vars ) {
    $key = array_search( 'old_query_var', $public_query_vars );
    if ( false !== $key ) {
        $public_query_vars[$key] = 'new_query_var';
    }
    return $public_query_vars;
}
add_filter( 'query_vars', 'modify_query_var' );

This example replaces the ‘old_query_var’ with ‘new_query_var’ in the list of allowed query variables.

Adding Multiple Query Variables

function add_multiple_query_vars( $public_query_vars ) {
    $new_vars = array( 'first_custom_query_var', 'second_custom_query_var' );
    $public_query_vars = array_merge( $public_query_vars, $new_vars );
    return $public_query_vars;
}
add_filter( 'query_vars', 'add_multiple_query_vars' );

In this example, we add two custom query variables (‘first_custom_query_var’ and ‘second_custom_query_var’) to the list of allowed query variables.

Checking if a Query Variable Exists

function check_query_var_exists( $public_query_vars ) {
    if ( in_array( 'custom_query_var', $public_query_vars ) ) {
        // The 'custom_query_var' exists in the list of allowed query variables
    } else {
        // The 'custom_query_var' does not exist in the list of allowed query variables
    }
    return $public_query_vars;
}
add_filter( 'query_vars', 'check_query_var_exists' );

This example checks if the ‘custom_query_var’ exists in the list of allowed query variables and performs an action based on the result.