Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jeremyboggs/871595 to your computer and use it in GitHub Desktop.
Save jeremyboggs/871595 to your computer and use it in GitHub Desktop.
Pseudo-elegant way to flush rewrite rules after creating a custom post type.
<?php
/**
* Example for writing a WP plugin that adds a custom post type and flushes
* rewrite rules only once on initialization.
*/
/**
* On activation, we'll set an option called 'my_plugin_name_flush' to true,
* so our plugin knows, on initialization, to flush the rewrite rules.
*/
function my_plugin_name_activation() {
add_option('my_plugin_name_flush', 'true');
}
register_activation_hook( __FILE__, 'my_plugin_name_activation' );
/**
* On deactivation, we'll remove our 'my_plugin_name_flush' option if it is
* still around. It shouldn't be after we register our post type.
*/
function my_plugin_name_deactivation() {
delete_option('my_plugin_name_flush');
}
register_deactivation_hook( __FILE__, 'my_plugin_name_deactivation' );
/**
* Register our post type. Specifically, we'll check if our
* 'my_plugin_name_flush' option is true. If so, we'll flush the rewrite rules,
* then delete the option, so it only flushes the rules once.
*/
function my_plugin_name_register_post_types() {
// Register code for your new post type here...
// register_post_type( 'custom_post_type_name', $customPostTypeDefs );
// Check the option we set on activation.
if (get_option('my_plugin_name_flush') == 'true') {
flush_rewrite_rules();
delete_option('my_plugin_name_flush');
}
}
add_action( 'init', 'my_plugin_name_register_post_types' );
@doolin
Copy link

doolin commented Jan 15, 2012

I've seen something similar for plugins, it seems to be a little bit trickier dealing with custom post types.

If you haven't been following along with wp-hackers list, a fair bit of discussion on the list and blog posts has been revolving around what belongs in themes and what belongs in plugins. Probably worth reading up on it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment