'flush_rewrite_rules() not working with update_option_{$option}

Will someone please explain to me why flushing doesn't work in my case. I added a custom settings page with a default value, but it doesn't work when I hit save changes. I use the admin_init hook to register settings like this.

register_setting(
                'my_general', 
                'my_general_settings', 
                array(
                    'default'   => 'hello',
                ) 
            );

I added sections and fields, and those work. Now I am having a problem with this. If I update or save the settings, the update_option_my_general_settings doesn't work. It isn't flushing the rules. Here is the function code I used inside this hook.

if ( $old_value === 'hello' || $value === 'hello' ) {
                // Flush rules
                flush_rewrite_rules();
            }

Remember I am supplying these arguments to the function $old_value, $value, $option

The filter mod_rewrite_rules adds the data to .htaccess after I manually refresh the permalinks inside settings. But the flush_rewrite_rules() doesn't seem to be refreshing the permalinks automatically.

What I want is that when the user updates the settings, the flush_rewrite_rules should be populated.

I really appreciate any help you can provide.



Solution 1:[1]

Just stumbled on this very issue. It indeed seems as if flush_rewrite_rules(); doesn't work in some cases. Haven't found out why yet, but here is the solution that does work for me:

add_action( 'update_option_myOptionName', function($old_value, $value){
    if(some_checks){
        delete_option( 'rewrite_rules' );
    }
}, 10, 2);

This approach found on (https://developer.wordpress.org/reference/functions/flush_rewrite_rules/) inforces the deletion of the cached rewrite rules and wordpress regenerates them whenever appropriate.

Hope that helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kossi D. T. S.