简体   繁体   English

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

[英]How to add rules in .htaccess via WordPress function

I am trying to add rules in .htaccess via WordPress function which works perfect but always need to update permalink structure to get it added in .htaccess. 我正在尝试通过WordPress功能在.htaccess中添加规则,该功能可以完美运行,但始终需要更新永久链接结构才能将其添加到.htaccess中。 How can I refresh / reload .htaccess automatically so that new rules can be added without updating permalink structure. 如何自动刷新/重新加载.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');

When I say I have to update permalink structure, I mean I have to go to WP Dashboard > Settings > Permalinks and have to click 'Save' 当我说必须更新永久链接结构时,我的意思是我必须转到WP Dashboard>设置>永久链接,并且必须单击“保存”

You can use the flush_rules() WP function to refresh the rewrite rule cache programatically (which also updates the .htacccess), without going to Settings -> Permalinks and having to click save. 您可以使用flush_rules() WP函数以编程方式刷新重写规则缓存(这也会更新.htacccess),而无需转到“设置”->“永久链接”,也不必单击“保存”。

Please, note that it is not recommended to call this function on each page load, because it can greatly reduce performance. 请注意,不建议在每次加载页面时调用此函数,因为它会大大降低性能。 Instead, make sure that it is called only when necessary. 相反,请确保仅在必要时才调用它。

For more information about it, you can refer to this codex link: http://codex.wordpress.org/Rewrite_API/flush_rules 有关此信息的更多信息,您可以参考以下Codex链接: http : //codex.wordpress.org/Rewrite_API/flush_rules

EDIT Use the following code to flush the rules on plugin activation. 编辑使用以下代码刷新插件激活规则。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM