add_rewrite_rule: $matches var not replaced by captured value

I want to access a plugin file (when <a> is clicked) without exposing actual path of the file. I am using the following rewrite rule:

add_rewrite_rule( 'continue/([0-9]+)/?$', 'wp-content/plugins/my-plugin/continue.php?where=$matches[1]', 'top' );

The request is redirected to continue.php but I always get $_GET['where']=$matches[1] instead of $_GET['where']=123 inside continue.php. It should have been replaced by some number.

Read More

I want something similar to this

Update

I have tried Monkeyman Rewrite Analyzer but my rule does not show up in it. Then why am I being redirected to the correct page?

e.g. for continue/2 it has the following output:

(.+?)(/[0-9]+)?/?$ pagename: continue page: /2

Related posts

Leave a Reply

1 comment

  1. That rewrite rule won’t work at all, flushed or not.

    There’s two kinds of rewrite rules in WordPress. Those that have their rewrite urls start with index.php and those that don’t.

    All WordPress internal rewrite rules must start with index.php. It can’t redirect to anyplace else, because it’s already been redirected to the index.php file by the time the WordPress functions are processing the ruleset. So non-index.php rules have to go into the .htaccess directly, so that they can be redirected to anywhere other than index.php.

    • Those that start with index.php will be processed inside WordPress itself, and the $matches[1] syntax will be the correct one to use in that case.

    • Those that don’t start with index.php will instead be written to the .htaccess file as direct RewriteRules. The $matches[1] syntax makes no sense in that case.

    If you look in your .htaccess file after using your rule, you’ll find this:

    RewriteRule continue/([0-9]+)/?$ wp-content/plugins/my-plugin/continue.php?where=$matches[1]
    

    Which obviously won’t work.

    Instead, try making your code into this:

    add_rewrite_rule( 'continue/([0-9]+)/?$', 'wp-content/plugins/my-plugin/continue.php?where=$1');
    

    Note the $1 replacement instead? This will work properly when converted to a normal RewriteRule.