Passing variable to page template with Mod Rewrite
-
I have a page template in my custom theme which loads a staff directory from a database outside of Word Press. What I am hoping to do is to be able to load information from the directory using their last name in a URL, by passing a variable to my staff directory template through the query string via Mod Rewrite. For example http://www.mysite.com/directory/staff-name/ would load my template http://www.mysite.com/my-template.php?staff_name=staff-name.
In my functions.php file I first add the variable use the add_rewrite_tag function. For example:
add_rewrite_tag('%staff_name%','([^&]+)');I then set up my rewrite rule using the add_rewrite_rule function. For example (page 201 is the page which uses my directory page template):
add_rewrite_rule('^directory/([\-_0-9A-Za-z]+)/?','index.php?p=201&staff_name=$matches[1]','top');Lastly in my directory template I attempt to recover the value of the staff name variable from the query string. For example:
$staff_name = $wp_query->query_vars['staff_name'];Here is what happens when I try to access the directory template via a url:
1. I enter http://www.mysite.com/directory/my-staff-name/.
2. The rewrite rule appears to be recognized, however it appears to forward me to the page with the title of the page in the address bar. For example I end up with http://www.mysite.com/my-page-title/, which is the permalink for p=201 which I put in my rewrite rule.
3. The staff name variable is empty when I try to retrieve it from the query string.
Can anyone give me an idea of what I am doing wrong here? Basically what I would like it to do is when I enter http://www.mysite.com/my-staff-name/, I want this address to stay in the address bar while I am redirected to my directory page template passing it the staff members name through the query string.
Thanks for you help!
The topic ‘Passing variable to page template with Mod Rewrite’ is closed to new replies.