WordPress: Refresh permalink structure with flush_rewrite_rules()

This is a quick one, but file it away in your brain and some day you’ll thank me. Have you noticed that when you create a new custom post type that you’ve gotta hit the admin settings and re-save your permalink structure? You don’t have to change anything, just saving it again will do the trick, but it’s an annoying little step.

If you’re creating post types programmatically (inside your plugin, whatever), you might need a way to automatically flush your rewrite rules. Enter the simple function flush_rewrite_rules().

flush_rewrite_rules( $hard );

The function only accepts one parameter, a boolean true/false for $hard, which will decide whether to actually update the rules in the .htaccess file or just soft flush the rewrite_rules transient. The default is true, meaning you’ll get a full flush.

Even if you’re not working with post types, you’ll sometimes run into scenarios when you need to flush. I’ve got a project going right now where I’ve dropped the author prefix in the URL, giving each user a top level page (domain.com/user). I noticed that these rules weren’t being created upon registration and a simple flush_rewrite_rules() in my registration hook fixed things up.

It’s worth noting that this is an “expensive” process, meaning you shouldn’t just run it all willy nilly. Only call this when you absolutely need it. If you’re not sure if you need it, you probably don’t. But six months from now when you can’t figure out why some users are hitting 404s, come back for a high five.