When you create a custom post type within WordPress, a permalink structure is built automagically for you. For example, if you create a custom post type of “Movies”, then you will automatically create a custom permalink structure that looks like: “http://www.yoursite.com/movies/”.
However — you may notice that you get a 404 page not found error after enabling the custom post type for the first type. Fear not – there are easy ways around this.
Cause of the WordPress 404 error for Custom Post Type Permalinks
This is caused by WordPress’s built in caching of the Permalink structure. From the WordPres codex page on Post Types (https://codex.wordpress.org/Post_Types)
This means that after a custom post type is defined in WordPress for the first time, the rewrite rules need to be refreshed. If you do nothing, these rewrite rules will be refreshed eventually – but best to do it and not wait for it.
Refreshing WordPress Rewrite Rules Manually
The fastest and easiest way to refresh your WordPress Rewrite rules is to go to “Settings” -> “Permalinks” and save your permalink settings. This will automatically cause a refresh of your rewrite rules.
Refreshing Programmatically to Fix Permalinks
If you want to refresh your WordPress rewrite rules via code, then you can do so using the following function:
This function is intensive, so don’t place it in a spot that will cause performance issues. For example, do not place this in the INIT action hook, as that will be called too often.
Notes for WordPress Plugin Developers
If you are developing a plugin and have created a custom post type – then you will need to deal with refreshing the rewrite rules as part of your plugin installation.
In order to do this – you will need to call the rewrite function during your plugin activation. However, your custom post types might not be defined yet, especially if you are using the init action hook to define your custom post type.
To get around this, you will need to define your custom post type during activation as well as during init. That way you can flush the rewrite rules as part of the install routine.
To help keep your plugin organized, you might want to abstract the custom post type declarations into their own function, then simply call that function from both your activation and init hooks in WordPress.