How do you permanently remove default rewrite rules from the wp_options table?

We have tons of rewrite rules saved in our wp_options table and I’d like to permanently remove any entries that we’re not using on our site (such as comment feeds, page attachments, etc.).

What’s the best way to clear these rules and prevent them from being saved to the database the next time flush_rules() is called? I’d prefer a solution that works in functions.php or as a standalone plugin, rather than editing core WP files such as wp-includes/rewrite.php.

Related posts

Leave a Reply

2 comments

  1. Rather than modifying stored rules it would be more reliable to modify rules before they are stored.

    • flush_rewrite_rules() calls
    • WP_Rewrite->flush_rules()
    • WP_Rewrite->wp_rewrite_rules()
    • WP_Rewrite->rewrite_rules()

    Inside last there are fitting hooks to modify rules (after which result they will be saved as usual on each flush):

    do_action_ref_array('generate_rewrite_rules', array(&$this));
    $this->rules = apply_filters('rewrite_rules_array', $this->rules);
    
  2. To do what you want you are going to have to add_rewrite_rule for each rule you have.
    I am storing new rules that users add to an options array.
    If the user wants to delete the rule, then once selected, I unset it from the array.

    function remove_rule($user_input){
        foreach($rules as $key => $rule){
            if($rule === $user_input){
                unset($rules[$key]);
            }
        }
        return $rules;
    }
    

    Then again rebuild your htaccess by adding all stored rules

    foreach($rules as $rule){
        add_rewrite_rule($rule['pattern'], $rule['url'], 'top');
    }
    

    Hope this helps anyone that needs it.