{"id":715,"date":"2013-01-21T14:00:35","date_gmt":"2013-01-21T13:00:35","guid":{"rendered":"https:\/\/wprealm.com\/?p=715"},"modified":"2017-12-27T19:43:47","modified_gmt":"2017-12-27T18:43:47","slug":"wordpress-rewrite-rules-human-made-core-style","status":"publish","type":"post","link":"http:\/\/wprealm.local\/wordpress-rewrite-rules-human-made-core-style\/","title":{"rendered":"WordPress Rewrite Rules, Human Made Core Style!"},"content":{"rendered":"

The WordPress rewrite system is an area many people struggle with when starting out. People not familiar with rewrite systems don’t necessarily understand what role they play and often developers who are used to using rewrite systems find WordPress’s implementation somewhat clunky.<\/p>\n

When working on relatively complex WordPress projects, which have multiple custom taxonomies and combinations of post types, custom rewrite rules are likely to be needed.<\/p>\n

\"\"<\/p>\n

So, what are rewrite rules<\/strong>? In WordPress, a rewrite rule is essentially a map of a URL pattern (using regex) to the WP_Query arguments. When the URL regex pattern is matched, the global $wp_query<\/code> is populated with the arguments of the rule. For example, a year archive “page” would have a rewrite rule like:<\/p>\n

^([d*4])\/?$ => year=$matches[1]<\/code><\/pre>\n

Now, to add your own custom rewrite rules, you have hook into potentially several places. Firstly you must hook into flush_rewrite<\/code> to add your regex => wp_query<\/code> arguments:<\/p>\n

add_rewrite_rule( '#some regex#', 'post_type=offer&posts_per_page=5' );<\/code><\/pre>\n

Some things to note:<\/p>\n

    \n
  • If you want to do any more advanced wp_query args that you can not pass in the string args style, or dynamically set arguments, you will need to hook into parse_request.<\/li>\n
  • If you have used any non-standard public query vars in your wp_query arguments you will need to hook into public_query_vars and add them to the array.<\/li>\n
  • Then you will need to hook into template_redirect to load a custom template for that URL pattern (if you so wish).<\/li>\n<\/ul>\n

    As a large amount of the work that I do is with quite complex relationships of post types and taxonomies, I have wrapped all the rewrite and associated functionality into a simple API, called hm_add_rewrite_rule.<\/p>\n

    The function takes an array of arguments about the specific rewrite rule, though the interface is all via one function call, it is backed by a pretty modular object orientated approach. A brief rundown of the argument<\/p>\n\n

    \n
    \n
    \n
    \n
    \n \n
    \n\n \n
    \n\n