I’m using the Settings API to allow the user to toggle the has_archive
option on some custom post types. When the user turns archives on or off, I want to flush the rewrite rules. If I had written the saving function myself, I could just call flush_rewrite_rules()
and be done with it, but the Settings API takes care of the saving for me. Is there a hook somewhere that I can use?
Chosen Solution @Stephen Harris
add_action('admin_init', 'my_plugin_register_settings');
function my_plugin_register_settings() {
if (delete_transient('my_plugin_flush_rules')) flush_rewrite_rules();
register_setting('my_plugin', 'my_plugin_settings', 'my_plugin_sanitize');
// add_settings_section(), add_settings_field(),...
}
function my_plugin_sanitize($input) {
set_transient('my_plugin_flush_rules', true);
return $input;
}
You simply need to visit the Settings > Permalink page (you don’t have to do anything there) after saving the settings.
Not quite.
flush_rewrite_rules()
would have to be called after the custom post type is ‘updated’ to reflect the changes, that is, after you register it. So you would need to call it on the next page load, after the CPT is registered.You could use a transient to trigger flush_rewrite_rules() on the next (and only the next)
init
(and after CPT is registered). To be clear,flush_rewrite_rules()
is expensive and shouldn’t be called regularly, this is why I suggest simply telling your plug-in users to visit the Settings > Permalink page after altering any permalink options – that way the rules get flushed only when its really needed.