public

Pseudo-elegant way to flush rewrite rules after creating a custom post type.

  • Download Gist
custom-post-type-flush-rewrite-rules.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
<?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' );

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.