WordPress custom post types breaks permalink on theme reinstall

This is a pretty strange problem. I’m creating a WordPress custom post type in my themes functions.php file using the following format:

add_action('init', 'product_register');

function product_register() {
$args = array(
    'label' => __('Products'),
    'singular_label' => __('Product'),
    'public' => true,
    'show_ui' => true,
    'capability_type' => 'post',
    'hierarchical' => false,
    'rewrite' => true,
    'supports' => array('title', 'editor', 'thumbnail')
);

register_post_type( 'product' , $args );
}

This gives me the following url structure for my products: http://www.mywebsite.com/products/product-name.

Read More

However, if I switch to another theme (TwentyTen) and then switch back WordPress forgets the permalink, now when I browse to the URL above I get my 404 page.

The really strange thing I’ve noticed is that I can fix this issue by browsing to Settings -> Permalinks in admin. This temporarily fixes the problem until the next theme uninstall/ reinstall.

Anyone else had a similar issue?

Related posts

Leave a Reply

1 comment

  1. The new permalink structure is only saved when WP_Rewrite::flush_rules() is called. Because this is an expensive operation (calculating the new rules and saving them to the database), you should not do it on every init call, but only when you change the structure. The custom post type however must be registered at every init call, since it is saved in a PHP array in memory, not in the database (which is why it forgot the custom post when you switched themes: the permalink structure still existed but referred to a custom post type that was not loaded, giving an error).