WordPress: rewrite rules

WordPress allows theme and plugin developers to programmatically specify new, custom rewrite rules. add_rewrite_rule() allows you to specify additional rewrite rules for WordPress. It is most commonly used in conjunction with add_rewrite_tag() (which allows WordPress to recognize custom post/get variables).

Note that these rules are usually called inside the init hook. Furthermore, permalinks will need to be refreshed (you can do this from your admin under Settings > Permalinks) before the rewrite changes will take effect. Requires one-time use of flush_rules() to take effect.

Although the quick way to define rewrite rules is to include it in the init hooked function. But the init function will be called on every page load and therefore will slow down the pageload. A better way is to include it in a function called by register_activation_hook(), when the plugin is first activated.

Note: The add_rewrite_rule needs to remain within the init function, as the rule needs to be defined in case any other plugin flushed the rewrite rules, or a user saves the permalink settings page (as this also flushes the rewrite rules).

Leave a Reply