I added the following custom routes to WordPress:

function add_custom_rewrite_rules() {
    add_rewrite_rule( 'generate/?', 'index.php?custom_route=generate', 'top' );
    add_rewrite_rule( 'random/?', 'index.php?custom_route=random', 'top' );

add_action( 'init', 'add_custom_rewrite_rules', PHP_INT_MAX );

This is the callback function:

function custom_routes_handler() {

    $custom_route = get_query_var( 'custom_route' );

    var_dump( $custom_route);

    global $wp_rewrite;

    foreach ( $wp_rewrite->rewrite_rules() as $rule => $rewrite ) {
        echo $rule . ' => ' . $rewrite . '<br>';


I get the var_dump result of string(0) "". And in the listed routes I can see, among all other routes:

generate/?$ => index.php?custom_route=generate
random/?$ => index.php?custom_route=random

I also triggered the URL rewrites regeneration via Admin > Settings > Save permalinks.

The WordPress installation is in the root folder.

Why am I not getting the proper value for get_query_var( 'custom_route' )?


1 Answer 1


I encountered the same issue on a client project. If you haven't already, you'll need to add the query variable as a public query variable otherwise using get_query_var() won't work properly.

 * Adds the query var to public vars, making it accessible.
add_filter('query_vars', 'query_vars');
function query_vars($public_query_vars)
    $public_query_vars[] = 'custom_route';
    return $public_query_vars;

Using this filter will add custom_route to the public query variables, and you should be able to get it's value in your script.

For further reference: https://developer.wordpress.org/reference/hooks/query_vars/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.