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.

DATE2nd July, 2012

CATEGORIESposts

TAGS , ,

4 Comments

  1. I created a plugin to add a custom post type to a project I am working on and all seemed alright up to the point where I tried to upload images as featured thumbnails for that custom post type. The upload gives an error message “An error occurred in the upload. Please try again later.”, which eventually turns to a php error message saying ”
    Warning: Cannot modify header information – headers already sent by (output started at /home/shost/rhythmunplugged/wp-content/plugins/photo-album/photo-album.php:13) in /home/shost/rhythmunplugged/wp-includes/pluggable.php on line 876″

    Any ideas on how to fix this?

  2. Stan

    *high five* You saved me a ton of work!

  3. How do you add the flush_rewrite_rules to a registration hook.

  4. how “expensive” is it? I wanna use it everytime a new post is created/edited

Leave a Reply