Flushing Custom Permalink Structure for Custom Post Type

Using custom permalink with custom post types result in 404s unless you flush the rewrite rules. Flushing the rewrite rules is a performance intensive function and should be used only the first time custom post/taxonomy type is registered.

Custom post types are a powerful feature of WordPress, however if you are using custom permalink with custom post type, You may end up getting 404. The simple solution is flushing the rewrite rules.

By flushing the rewrite rules it means to remove the existing rewrite rules and recreate the new ones. To achieve this you can do so by:

  • Simply visiting the Settings>Permalinks page in WP-Admin of your website and hitting up ‘Save Changes’ button.
  • By using the flush_rewrite_rules() function.

Using flush_rewrite_rules()

flush_rewrite_rules( $hard = true ) has an optional parameter which can be set to either
TRUE : for hard flush including rewriting of .htaccess file or
FALSE : for soft flush that involves flushing the transient rules.

Usage inside Plugins

For using it inside plugins, hook this function to plugin activation like the following :

 

This fire the flush_rewrite_rules() only once plugin is activated.

Using inside Themes

Similarly you can flush the rewrite rules on theme activation like following :

 

Remember that you may find flush_rewrite_rules hooked to “init” which is wrong. Running flush_rewrite _rules on hooks which fire on every page load will make your website slow to load. This function should only be used when custom post types are defined for the first time.