Edit .htaccess on plugin deactivate

2019-08-28 10:10发布

问题:

  1. I am trying to add rewrite rules in .htaccess during plugin activation. How can I edit/roll-back rewrite rules in .htaccess on plugin deactivation?

    function add_to_htaccess( $rules ) {
        $content = <<<EOD
        \nAddOutputFilterByType DEFLATE text/plain
        AddOutputFilterByType DEFLATE text/html
        AddOutputFilterByType DEFLATE text/xml
        AddOutputFilterByType DEFLATE text/css
        AddOutputFilterByType DEFLATE application/xml
        AddOutputFilterByType DEFLATE application/xhtml+xml
        AddOutputFilterByType DEFLATE application/rss+xml
        AddOutputFilterByType DEFLATE application/javascript
        AddOutputFilterByType DEFLATE application/x-javascript
        AddOutputFilterByType DEFLATE application/x-httpd-php
        AddOutputFilterByType DEFLATE application/x-httpd-fastphp
        AddOutputFilterByType DEFLATE image/svg+xml
        SetOutputFilter DEFLATE\n\n
        EOD;
        return $content . $rules;
    }
    add_filter('mod_rewrite_rules', 'add_to_htaccess');
    
    function myplugin_enable_flush_rules() {
        global $wp_rewrite;
        $wp_rewrite->flush_rules();
    }
    register_activation_hook( __FILE__, 'myplugin_enable_flush_rules' );
    
  2. The above function adds rewrite rules with in default WordPress rules lies between # BEGIN WordPress and # END WordPress. What could I do to add it separately (at the bottom of .htaccess ?)

回答1:

I have managed to do this at my own. Below is the function I have added.

function myplugin_deactivate() {
    // This will remove the rewrite rules
    remove_filter('mod_rewrite_rules', 'add_to_htaccess');

    global $wp_rewrite;

    // Flush the rewrite rules
    $wp_rewrite->flush_rules();
}
register_deactivation_hook( __FILE__, 'myplugin_deactivate' );