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.

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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).


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x