最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

hooks - How do I flush the rules after saving settings using the Settings API?

programmeradmin1浏览0评论

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;
}

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;
}
Share Improve this question edited Feb 5, 2022 at 17:25 arafatgazi 2052 silver badges4 bronze badges asked Apr 2, 2012 at 22:25 MattMatt 4651 gold badge5 silver badges13 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 5

You simply need to visit the Settings > Permalink page (you don't have to do anything there) after saving the settings.

If I had written the saving function myself, I could just call flush_rewrite_rules()

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.

发布评论

评论列表(0)

  1. 暂无评论