Rewriting WordPress URLs from the Ground Up

If you’re creating an application that uses WordPress for other than a blogging platform, then you might want to consider throwing out its default URL rules. I’ll use my Savory Bookmarks as an example.

Savory uses custom post types to store bookmarks. This means that the WordPress LOOP has to be completly sidetracked to instead query for this post type instead of standard blog posts. In fact, the Savory application does NOTHING with blog posts, archives and categories. So, why not clean up the URL rules and make sure nobody is taking backdoors to unforeseen 404 pages.

There are lots of filters for handling URL re-write rules, but since we’re starting from scratch, we’ll use rewrite_rules_array filter.


add_filter('rewrite_rules_array', 'url_rewrite_filter');

function url_rewrite_filter($rules) {
  $new_rules = array();

  // front page
  $new_rules['/?$'] = 'index.php?post_type=savorypost';

  // paged
  $new_rules['page/([0-9]{1,})/?$'] = 'index.php?post_type=savorypost&paged=$matches[1]';

  // tags
  $new_rules['tag/(.+)/?$'] = 'index.php?post_type=savorypost&tag=$matches[1]';
 
  // paged tags
  $new_rules['tag/(.+)/([0-9]{1,})/?$'] = 'index.php?post_type=savorypost&tag=$matches[1]&paged=$matches[2]';
  
  // single bookmarks
  $new_rules['savory/([^/]+)(/[0-9]+)?/?$'] = 'index.php?savorypost=$matches[1]&page=$matches[2]';
  
  return $new_rules;
}

The most critical step to get our custom post types to work, is to include the query parameter post_type=savorypost. And, by throwing away ALL the other re-write rules, we insure that ONLY our custom post types have the possibility to be queried and displayed.

When our rewrite_rules_array filter returns, it returns our NEW array of rules and basically throws away the default generated rules passed to it.

Oh, and you’ll have to update your permalink structure to fire this filter: Settings > Permalinks, click Save Changes.

Leave a Reply