如何通过WordPress函数在.htaccess中添加规则

时间:2014-08-22 17:22:01

标签: wordpress .htaccess mod-rewrite wordpress-plugin

我正在尝试通过WordPress功能在.htaccess中添加规则,该功能完美但总是需要更新永久链接结构以将其添加到.htaccess中。如何自动刷新/重新加载.htaccess,以便在不更新永久链接结构的情况下添加新规则。

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');

当我说我必须更新永久链接结构时,我的意思是我必须转到WP Dashboard&gt;设置&gt;永久链接,必须点击“保存”

1 个答案:

答案 0 :(得分:3)

您可以使用flush_rules() WP功能以编程方式刷新重写规则缓存(也会更新.htacccess),而无需转到设置 - &gt;永久链接,不得不点击保存。

请注意,建议不要在每次页面加载时调用此函数,因为它会大大降低性能。相反,请确保仅在必要时调用它。

有关它的更多信息,请参阅此codex链接:http://codex.wordpress.org/Rewrite_API/flush_rules

编辑使用以下代码清除插件激活的规则。

// calling this function will make flush_rules to be called at the end of the PHP execution
function myplugin_enable_flush_rules() {

    global $wp_rewrite;

    // flush the rewrite rules
    $wp_rewrite->flush_rules();

}

// on plugin activation, call the function that will make flush_rules to be called at the end of the PHP execution
register_activation_hook( __FILE__, 'myplugin_enable_flush_rules' );