Home  >  Article  >  Backend Development  >  WordPress中用于更新伪静态规则的PHP代码实例讲解_PHP

WordPress中用于更新伪静态规则的PHP代码实例讲解_PHP

WBOY
WBOYOriginal
2016-05-29 11:47:20891browse

flush_rewrite_rules() 函数用来删除然后根据现有的条件重写伪静态规则,也就是刷新一次伪静态规则了。

先来说一下,通常在主题或者插件添加新的自定义文章类型的时候调用,防止新的自定义文章类型的文章出现 404 的情况,或者很多时候我们都需要在主题启用的时候执行一些代码,比如布置一些数据库表单、跳转到设置页面等等,WordPress 本身并没有提供相关的钩子,网上也有很多五花八门的实现方法,经过我的研究,发现了可能是最优的方法,下边分享给大家:

/**
  *WordPress 在主题启用的时候执行一些代码
  *http://www.endskin.com/theme-activation-action/
*/
function Bing_theme_activation(){
  if( $GLOBALS['pagenow'] != 'themes.php' || !isset( $_GET['activated'] ) ) return;
  /*
  这里就可以放置在主题启用的时候要执行的代码了,比如跳转到设置界面:
  wp_redirect( admin_url( 'options-general.php' ) );//注意修改页面地址
  die;
  */
}
add_action( 'load-themes.php', 'Bing_theme_activation' );

此代码放在主题和插件里都是有效的。

另外要注意,更新伪静态规则是非常消耗时间和效率的,所以不要每次执行代码都调用,只在必要的情况调用(比如启用主题和启用插件),把 flush_rewrite_rules() 挂到 init 钩子上是极其不正确的。

用法

flush_rewrite_rules( $hard );

参数

$hard

(布尔)(可选)如果为 True 则一起刷新 .htaccess 文件(hard flush);为 False 则只更新数据库里的伪静态规则(soft flush)。

默认值:True(hard flush)。

例子

在主题启用的时候更新伪静态规则:

function Bing_theme_activation(){
  if( $GLOBALS['pagenow'] != 'themes.php' || !isset( $_GET['activated'] ) ) return;
  flush_rewrite_rules();
}
add_action( 'load-themes.php', 'Bing_theme_activation' );

在插件启用的时候更新伪静态规则:

function Bing_myplugin_activate(){
  flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'Bing_myplugin_activate' );


其它

此函数位于:wp-includes/rewrite.php

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn