I'm trying to do a redirect feature in a plugin and i have an issue. First, the code:

add_action( 'init', function(){
    add_rewrite_rule( 'go/([^/]+)/?$', 'index.php?redirect_to=$matches[1]', 'top' );
    add_rewrite_tag( "%redirect_to%", '([^&]+)' );`
} );

Ok, so, the rule is set. The tag is set. If i'm using get_query_var('redirect_to') inside of functions.php (or anywhere in the theme actually) it works, but if i'm trying to use the same query var from the plugin files, it silently fails. And since it's a plugin, there is no way to ask users to edit their themes :)

Things i did:

  • i'm using it inside of init hook set as priority 999
  • it works if i use wp_head instead of init, but this way i can't do the redirect anymore
  • i flushed rewrite rules

So, my question is: how do i use the damn get_query_var('redirect_to') inside of my plugin files?


  • 1
    I believe that init is too early, as the query_vars haven't been set yet. Have you tried hooking into the parse_query action?
    – Will
    Jun 28, 2014 at 13:35
  • yes! this works. please add is as a post to be able to select it as the correct answer. Thanks a lot! Jun 28, 2014 at 15:49

1 Answer 1


Hook into parse_query instead:

add_action( 'parse_query', function() {
    add_rewrite_rule( 'go/([^/]+)/?$', 'index.php?redirect_to=$matches[1]', 'top' );
    add_rewrite_tag( "%redirect_to%", '([^&]+)' );`
} );

Reason: init is too early, query_vars haven't been set yet. wp_head is too late, no can redirect at that point.

  • Actually rewrite rules should be added on init. But parse_query is the right hook to to retreive the bastard! Jun 28, 2014 at 15:59
  • glad you got it worked out!
    – Will
    Jun 28, 2014 at 16:03

Your Answer

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

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