WordPress page rewrite
Lately I was working on rewriting a WP page url so that the browser address that is loaded by a user doesn’t changes but internally the request is sent to some other page.
After spending hours on this and trying every possible .htaccess rules that I have knowledge of I finally came accross this super amazing WP class called WP_Rewrite.
Although the life didn’t become much easy when I found this class, but I had this feeling some where deep inside me that this class of WP will prove to be a life saver for me.. and yes it did!
What I was trying:
1) User loads a url:
and gets served a page which actually resides here:
without the url in address bar getting changed.
What did the trick:
I added a WP filter called page_rewrite_rules, and coded a method which added my custom rewrite rules to the array of WP rewrite rules.
The code is something like this:
add_filter( ‘page_rewrite_rules’, ‘my_page_rewrite_rules’ );
function my_page_rewrite_rules( $rewrite_rules )
// The most generic page rewrite rule is at end of the array
// We place our rule one before that
end( $rewrite_rules );
$last_pattern = key( $rewrite_rules );
$last_replacement = array_pop( $rewrite_rules );
$rewrite_rules += array(
‘first-post/hello-world/?$’ => ‘index.php?pagename=hello-world’,
$last_pattern => $last_replacement,
Now to make this rule apply to your WP installation, you need to flush out the existing rewrites so that new rewrites are generated. I avoided a little coding here and followed this procedure:
1) Go to your site’s permalink settings.
2) Change your settings to default and save.
3) Change your settings to YOUR OWN CUSTOM SETTINGS that you are using on your website.
The above 3 steps will flush and re-create the rewrite rules for your site and the new rewrite will come into effect.