flush_rewrite_rules()

更新伪静态规则

描述

删除重写规则,然后重新创建重写规则。

此功能在与自定义帖子类型一起使用时很有用,因为它允许自动刷新WordPress重写规则(通常需要手动完成新的自定义帖子类型)。但是,这是一项昂贵的操作,因此应仅在绝对必要时使用。有关更多详细信息,请参阅“用法”部分。

用法

重要:

刷新重写规则是一项昂贵的操作,有一些教程和示例建议在“init”钩子上执行它。这是不好的做法。

仅在激活或停用时刷新规则,或者当您知道需要更改重写规则时刷新规则。不要在任何会定期触发的钩子上执行此操作。WP工程师帖子评论中的更多详细信息:自定义帖子类型和永久链接

在刷新重写规则之前,请确保自定义帖子类型和分类已正确注册,尤其是在插件激活期间:WordPress插件开发人员的激活清单

<?php flush_rewrite_rules( $hard ); ?>

参数

$hard

(boolean) (可选) Whether to update .htaccess (hard flush) or just update rewrite_rules transient (soft flush).
(布尔值)(可选)是更新 .htaccess(硬刷新)还是仅更新瞬态rewrite_rules(软刷新)。

默认值: true (hard flush)
默认值: true (hard flush)

示例

This is how you would flush rewrite rules when a plugin is activated or deactivated:
这是激活或停用插件时刷新重写规则的方式:

register_deactivation_hook( __FILE__, ‘flush_rewrite_rules’ );
register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );

register_activation_hook( __FILE__, ‘myplugin_flush_rewrites’ );
register_activation_hook( __FILE__, 'myplugin_flush_rewrites' );

function myplugin_flush_rewrites() {
函数 myplugin_flush_rewrites() {

// call your CPT registration function here (it should also be hooked into ‘init’)
在此处调用您的 CPT 注册函数(它也应该挂接到“init”中)

myplugin_custom_post_types_registration();
myplugin_custom_post_types_registration();

flush_rewrite_rules(); flush_rewrite_rules();

}

以下是刷新主题激活规则的方式:

/* Flush rewrite rules for custom post types. */
/* 自定义帖子类型的刷新重写规则。*/

add_action( ‘after_switch_theme’, ‘flush_rewrite_rules’ );
add_action( 'after_switch_theme', 'flush_rewrite_rules' );

如果您正在开发主题,在构建主题时,您可以使用以下代码片段,该代码片段将在包含该主题的文件发生更改时或每 48 小时刷新一次重写规则:

// do not use on live/production servers

add_action( ‘init’,‘maybe_rewrite_rules’ );

function maybe_rewrite_rules() {

$ver = filemtime( __FILE__ ); // Get the file time for this file as the version number

$defaults = array( ‘version’ => 0, ‘time’ => time() );

$r = wp_parse_args( get_option( __CLASS__ . ‘_flush’, array() ), $defaults );

if ( $r[‘version’] != $ver || $r[‘time’] + 172800 < time() ) { // Flush if ver changes or if 48hrs has passed.

flush_rewrite_rules();

// trace( ‘flushed’ );

$args = array( ‘version’ => $ver, ‘time’ => time() );

if ( ! update_option( __CLASS__ . ‘_flush’, $args ) )

add_option( __CLASS__ . ‘_flush’, $args );

}

}

历史

添加于 版本: 3.0

源文件

flush_rewrite_rules() 函数的代码位于 wp-includes/rewrite.php

/**
* Remove rewrite rules and then recreate rewrite rules.
*
* @since 3.0.0
*
* @global WP_Rewrite $wp_rewrite
*
* @param bool $hard Whether to update .htaccess (hard flush) or just update
*                  rewrite_rules transient (soft flush). Default is true (hard).
*/

function flush_rewrite_rules( $hard = true ) {

global $wp_rewrite;

$wp_rewrite->flush_rules( $hard );

}

原文:http://codex.wordpress.org/Function_Reference/flush_rewrite_rules

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索