WordPress: fix the 404 Error on custom post types

The infamous 404 Error (Not Found) raised on WordPress custom post types is due to the clash between your permalink structure and the rewrite parameter specified in the register_post_type() function. For example, if you have a permalink structure like /%year%/%monthnum%/%postname%/ and you specify the slug parameter, then WordPress will rewrite your custom post type URL as sitename.ext/post-type/post-name. This will lead to the 404 Error, because the two permalink structures don't match. Fortunately, there's a solution.

Suppose that you've created a portfolios custom post type:

function portfolios_custom_init() {
  $labels = array(
    'name' => _x('Portfolios', 'post type general name'),
    'singular_name' => _x('Portfolio', 'post type singular name'),
    'add_new' => _x('Add New', 'Portfolio'),
    'add_new_item' => __('Add New Portfolio'),
    'edit_item' => __('Edit Portfolio'),
    'new_item' => __('New Portfolio'),
    'all_items' => __('All Portfolios'),
    'view_item' => __('View Portfolio'),
    'search_items' => __('Search Portfolios'),
    'not_found' =>  __('No Portfolios found'),
    'not_found_in_trash' => __('No Portfolios found in Trash'), 
    'parent_item_colon' => '',
    'menu_name' => __('Portfolios')

  $args = array(
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true, 
    'show_in_menu' => true, 
    'query_var' => true,
    'rewrite' => array('slug'=>'portfolios'),
    'capability_type' => 'post',
    'has_archive' => true, 
    'hierarchical' => false,
    'menu_position' => 100,
    'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt')
add_action( 'init', 'portfolios_custom_init' );

The permalink generated will be sitename.ext/portfolios/portfolio. If your permalink structure doesn't match the custom post type permalink structure, do the following:

  1. Go to SettingsPermalinks and change your current structure to /%category%/%postname%.
  2. Save changes.
  3. Restore your original permalink settings.
  4. Save changes.

Now your custom post type permalink structure won't generate the 404 Error anymore.