I know there are several topics about URL rewriting in WordPress but none of the topics I found helped me.
I want to rewrite the URL
profile/?person=abc (which works fine, but isn't pretty)
to
profile/abc
This is what I added to the functions.php of my theme:
function add_rewrite_rules() {
global $wp_rewrite;
add_rewrite_rule('profile/([^/]+)/?$', 'index.php?pagename=profile&person=$matches[1]', 'top');
$wp_rewrite->flush_rules(false);
}
add_action('init', 'add_rewrite_rules');
function add_query_vars() {
global $wp;
$wp->add_query_var('person');
}
add_action('init', 'add_query_vars');
When I try to call
mydomain.com/profile/abc
WordPress just changes the URL to
mydomain.com/profile
Of course ‘person’ is not among the query vars when I try to access them.
I also tried to write everything in one function (which shouldn’t make any difference) and to add the query var ‘person’ to the query array with the query_vars filter hook:
function add_query_vars($q) {
$q[] = 'person';
return $q;
}
add_filter('query_vars', 'add_query_vars');
From everything I’ve read about URL rewriting with WP my code should work. I also tried deactivating all other plugins so nothing could interfere.
Solution
Since I can’t answer my question because of my reputation I write the solution here:
The reason was that I tried to redirect to a child page. I left that piece of information out in my code above because I thought it was unimportant, but in fact it was the reason for my issue. Sorry for that, I just wanted to clean my code up a bit :-/
The line that got it all working:
add_rewrite_rule('persons/profile/([^/]+)/?$', 'index.php?pagename=persons/profile&person=$matches[1]', 'top');
What I don’t understand is why I didn’t get any error messages (WP_DEBUG was set to true) and got redirected to the right page (just without query parameter).