The last couple days I’ve struggled with adding custom rewrite rules to WordPress so that a user can edit settings for their account on the front end. The code and methods are straight forward enough and can be found on the codex page. But I was running into an issue where when I went to the edit page and passed a custom parameter it would throw a 404 error. I dug through all the filters I could find having to do with query vars and every time I output the query vars I would see page_id=0 which was causing the 404. I could figure out why that variable was being set to 0. After hours of digging I was finally looking through the source of the WP class and found it calling a function called get_page_by_pathon the codex page I noticed that when it was called for a sub page the value would be passed in like so:
|
1 |
get_page_by_path('parent-page/sub-page'); |
The issue was that I was passing just the sub page page name in with my request.
|
1 2 3 4 5 |
function gcc_insert_rewrite_rules( $rules ){
$newrules = array();
$newrules['my-account/(edit-location)/(.*)/?$'] = 'index.php?post_type=page&pagename=$matches[1]&location_name=$matches[2]';
return $newrules + $rules;
} |
A simple change in the regular expression was all that was needed to get the correct page and stop the 404.
|
1 2 3 4 5 |
function gcc_insert_rewrite_rules( $rules ){
$newrules = array();
$newrules['(my-account/edit-location)/(.*)/?$'] = 'index.php?post_type=page&pagename=$matches[1]&location_name=$matches[2]';
return $newrules + $rules;
} |