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...
functions.php
Using WordPress theme functions (functions.php
), there are 2 steps to pass slash-based url as GET
parameters to a page, after any rewrite-rule change:
Flush rewrite rules == re-save permalink settings in admin!
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)
add_action('init', function(){
add_rewrite_rule(
'^yourPageSlug/([^/]+)([/]?)(.*)',
//!IMPORTANT! THIS MUST BE IN SINGLE QUOTES!:
'index.php?pagename=yourPageSlug&user=$matches[1]',
'top'
);
});
Arguments/Parameters:
index.php
(if it is not an external link), because all url rewriting in WordPress comes through it
pagename
GET
parameter set to your page slug
$matches[indexStartingFrom1]
for regexp match - which really'top' or 'bottom'. 'top' will take precedence over WordPress's existing rules, where 'bottom' will check all other rules match first. Default: "bottom"
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 custom query_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 a query_vars
filter
add_filter('query_vars', function( $vars ){
$vars[] = 'pagename';
$vars[] = 'user';
return $vars;
});
Then to get value of GET
param "user" use:
get_query_var( 'user' )
.htaccess
If you can, you can also use .htaccess
rule (considering, /mysite/
is your rewrite base)
RewriteRule ^pagename/([^/]+)$ pagename?user=$1
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With