I'm trying to write a custom rewrite rule and then to a redirect based on the last part of it:

add_filter('query_vars', 'a_add_query_vars');
add_action('init', 'a_rewrite_tags');
add_action('init', 'a_rewrite_rules');
add_action('init', 'a_download_token');

function a_rewrite_tags()
    add_rewrite_tag('%download-token%', '([^/&]+)');

function a_add_query_vars($public_query_vars)
    $public_query_vars[] = 'download-token';
    return $public_query_vars;

function a_rewrite_rules()
    add_rewrite_rule('^download/([^&/]*)/?', 'index.php?download-token=$matches[1]', 'top');

function a_download_token()
    if (is_admin()) {
    global $wp_query;

    if (!empty(get_query_var("download-token", null))) {
        //Unfortunately this won't be executed...

The Problem

I verified that the rewrite rule works (with Debug bar/Query Monitor), but the query_vars array of the $wp_query object is empty.

  • 1
    The query hasn't been parsed yet on init action. Also note that adding a rewrite tag adds the query var automatically, that part is redundant. – Milo Apr 12 '17 at 10:44
  • @Milo Thanks so far! Which event should I use then to hook into? – manniL Apr 12 '17 at 10:50
  • @Milo nvm, I used the "parse_query" hook. Thanks for everything! I'll accept your answer as correct when you create one ;) – manniL Apr 12 '17 at 11:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.