I am trying to pass a parameter to a wordpress page. I don’t want to pass it as a query string. I would like to pass as a slash based url.
Example:
http://localhost/mysite/pagename?user=myname
into
http://localhost/mysite/pagename/myname
How can I achieve this using my functions.php
file in wordpress custom theme?
Going through
rewrite_rules_array
seems unneeded – it is more for a rewrite rule kill/remove than for adding rules…USING
functions.php
Using WordPress theme functions (
functions.php
), there are 2 steps to pass slash-based url asGET
parameters to a page, after any rewrite-rule change:Flush rewrite rules == re-save permalink settings in admin!
Step 1 – add_rewrite_rule(…)
This might be a bit confusing, when trying to get it work, because documentation for
add_rewrite_rule(...)
is not quite clear on where to target the rewrite nor how to target a page by slug… and there is just an important note that you need to flush rewrite rules every time you change something like that…This works for me (WP 4.3.3)
Arguments/Parameters:
index.php
(if it is not an external link), because all url rewriting in WordPress comes through itpagename
GET
parameter set to your page slug$matches[indexStartingFrom1]
for regexp match – which reallyis just a placeholder! ==> use single quotes to wrap this string!
Step 2 – add
query_vars
Step above is just a targeting, not passing the variables itself…
Since WordPress would clear the
$_GET
parameters “as are” and just throw them away (because it would not find anything suitable for it), we need to tell the WordPress that we want to use them by adding our customquery_vars
.We will still not be able to retrieve them through
$_GET
superglobal, however,we will be able to get them using
get_query_var(...)
We tell WordPress that we want to use those
GET
parameters by adding aquery_vars
filterFinal step:
FLUSH REWRITE RULES == RESAVE PERMALINK SETTINGS!
Usage
Then to get value of
GET
param “user” use:USING
.htaccess
If you can, you can also use
.htaccess
rule (considering,/mysite/
is your rewrite base)Here’s a thorough tutorial that gets close: http://www.rlmseo.com/blog/passing-get-query-string-parameters-in-wordpress-url/
In short, you define some new rewrite rules, and then hook them into WordPress via
add_filter('rewrite_rules_array', 'my_rewrite_rules');
However, following that link’s example, your resulting URL would be
http://localhost/mysite/pagename/user/myname
– note that /user/ (the name of your query variable) is still included.