0

In my functions.php of my theme I'm registering 5 custom post types. Each having a custom taxonomy, which I'm rewriting the url based upon. Meaning the custom post URL becomes http://example.com/cpt-slug/taxonomy-name/cpt-name.

For example the post "Childrens book no. 1" of the custom post type "books" with the category "Childrens books" would become http://example.com/books/childrens-books/childrens-book-no-1.

Whenever I register a new post type I need to flush the rewrite rules in order to get the permalink taxonomy rewrite to work.

So in order to not use flush_rewrite_rules() more often than needed, when do I use it?

I understand theres a registered_post_type() hook, but it seems to fire every time the admin is reloaded, making it a rather resource consuming operation.

Is there a hook that only fires when a new post type is registered?

0

Post types are registered on every load. They're not stored in the database or some other sort of persistent storage. The posts are, but not the post types.

So the correct place to flush rewrite rules is when the theme is activated. This can be done with the after_switch_theme hook:

add_action( 'after_switch_theme', 'flush_rewrite_rules' );

For a plugin, you'd do it with the activation and deactivation hooks:

register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );
register_activation_hook( __FILE__, 'flush_rewrite_rules' );
  • Would this not mean that the flush_rewrite_rules() is only run when the theme is activated? I'm using a child them of GeneratePress, So technically the theme should never be deactivated, nor reactivated. But i suppose your answer would be the ideal scenario for theme development. I will probably be the one adding more CPTs in the future, so obviously i can flush manually. I was just wondering if there was a hook for my scenario. Your answer is perfect for a more ideal theme setup anyways. So thanks for the insight. – Emil Østervig Sep 19 '17 at 8:48
  • Normally custom post types wouldn't be getting added during a theme's lifetime, so you'd only need to flush when the theme is first installed. If post types were added during regular use it would typically be on some user action, like saving an options page, in which case you would flush rewrite rules then. The Codex article on flush_rewrite_rules offers a suggestion for more frequent flushing during development, but it shouldn't be necessary during production. – Jacob Peattie Sep 19 '17 at 8:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.