Going Beyond with Permalinks and Rewrites

I am not writing a guide here, but I am writing notes for how to get more out of permalinks and URI rewrites. When I switched all of my site to WordPress 1.5, I wrote custom rewrite rules in the .htaccess file to maintain the important URIs. (I milked the mention of my website in a book to possible employers.)

The schemes mapping URIs to pages

  1. http://moronicbajebus.com/playground/ => category page for Playground
  2. http://moronicbajebus.com/playground/ => category page for categories which are children of Playground
  3. http://moronicbajebus.com/playground/ => post page for the post within the sub category

The short WordPress 1.5 implementation with .htaccess

RewriteRule ^(playground(/[^/]+)?)/page/?([0-9]{1,})/?$ /index.php?category_name=$1&paged=$3 [QSA,L]
RewriteRule ^(playground/[^/]+)/([^/]+)(/[0-9]+)?/?$ /index.php?category_name=$1&name=$2&paged=$3 [QSA,L]

(The longer version has about four rules for each for to support the RSS feed and etc.)

The changing implementation with WordPress 2

With WordPress 2, the WordPress 1.5 implementation does not work. WordPress 2 does not write all the rewrite rules to the .htaccess file. Instead, it uses a simple rewrite rule for the .htaccess file and then internally to the WordPress code figures out how to rewrite the code.

In my unenlightened state, I attempt to “fix” this by hacking wp-settings.php to check for rewrites made in the .htaccess file. This is not correct. The correct way is to use the internal hooks to the rewrite engine. Obviously, I searched for a plugin to do the dirty work for me which is what Custom Rewrite Rules does. (The site seems to be down so here is a mirrored copy.) In addition to Custom Rewrite Rule, WordPress Internal Rewrite Viewer Plugin is useful in showing you all the rewrite rules.

The WordPress 2 implementation with Custom Rewrite Rules

  1. ^(playground(/[^/]+)?)/? => index.php?category_name=$matches[1]
  2. ^(playground/[^/]+)/([^/])/? => index.php?category_name=$matches[1]&name=$matches[2]

I found that $matches[n] would work for back referencing whereas $n and \\n did not work. Also, the rewrite engine will automatically handle the multiple pages, such as /playground/cssplay/page/2/, for the rules. This helps explains why I ran into issues with placing a $ at the end.

I heistetated switching to WordPress 2 because I thought they had broken the feature and all my searches found page after page reaffirming this. But unknowingly, they did not break it–they refactored it.

Leave a Reply

All comments are moderated for approval after submission. Attention spammers do not waste your or my time by trying to comment.

Your Personal Information
Author Name .
Email Address .
Website Address .
Your Comment
Send Your Reply