I am trying to find pretty URL solution for url parameters.
Consider this url set
http://example.com?token=foo
http://example.com/pagename?token=foo
http://example.com/parent/childpage?token=foo
http://example.com/category/bar?token=foo
..
My Previous Code Example
add_action('template_redirect', function(){
if(!isset($_GET['token])){
return;
}
// run code
});
Need to move the whole thing into WordPress Pretty url.
Example pretty Urls with parameter
http://example.com/foo
http://example.com/pagename/foo
http://example.com/parent/childpage/foo
http://example.com/category/bar/foo
..
For a page this is the working Rewrite rule
add_rewrite_rule("([^/]*)/foo", 'index.php?pagename=$matches[1]&'. foo .'=1', 'top');
Which doesn’t seem to work for nested child pages. So for child pages upto 2 nested page. I have to add
add_rewrite_rule("([^/]*)/foo", 'index.php?pagename=$matches[1]&foo=1', 'top');
add_rewrite_rule("([^/]*)/([^/]*)/foo", 'index.php?pagename=$matches[1]/$matches[2]&foo=1', 'top');
add_rewrite_rule("([^/]*)/([^/]*)/([^/]*)/foo", 'index.php?pagename=$matches[1]/$matches[2]/$matches[3]&foo=1', 'top');
Is there any possible way to do it on single line of code so all pages, nested or parent, posts, archive links?
My end goal is to pass the extra foo
parameters. Other WordPress query vars remains same.
Full Gist for you to look into more details https://gist.github.com/prionkor/ef2e6b24d8d5561b4ad7
1 Answer
In order to add a parameter to all url of WordPress add_rewrite_endpoint()
is more appropriate.
I needed to add /foo
after all URL so add_rewrite_endpoint("foo", EP_ALL);
did the trick.