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:
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.
For using it inside plugins, hook this function to plugin activation like the following :
function myAwesomePlugin_activate() { // register taxonomies/post types here flush_rewrite_rules(); } register_activation_hook( __FILE__, 'myAwesomePlugin_activate' );
This fire the flush_rewrite_rules() only once plugin is activated.
Similarly you can flush the rewrite rules on theme activation like following :
function mytheme_activate() { flush_rewrite_rules(); } add_action( 'after_switch_theme', 'mytheme_activate' );
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.