WordPress函数:flush_rewrite_rules 刷新重写规则

江河/ 01月26日/ WordPress/ 浏览 1066

函数原型:


flush_rewrite_rules( bool $hard = true )


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


当与自定义帖子类型一起使用时,此功能非常有用,因为它允许自动刷新WordPress重写规则(通常需要为新的自定义帖子类型手动执行)。然而,这是一项昂贵的操作,因此只能在必要时使用。


参数说明:


$hard 是更新.htaccess(硬刷新)还是只更新rewrite_rules选项(软刷新)。默认为true(硬)。


函数源码:


function flush_rewrite_rules( $hard = true ) {
	global $wp_rewrite;

	if ( is_callable( array( $wp_rewrite, 'flush_rules' ) ) ) {
		$wp_rewrite->flush_rules( $hard );
	}
}


使用举例:


function wpdoc_flush_rules_on_save_posts( $post_id ) {

    // Check the correct post type.
    // Example to check, if the post type isn't 'post' then don't flush, just return.
    if ( ! empty( $_POST['post_type'] && $_POST['post_type'] != 'post' ) {
        return;
    }

    flush_rewrite_rules();

}

add_action( 'save_post', 'wpdoc_flush_rules_on_save_posts', 20, 2);


发表评论

暂无评论,抢个沙发...

客服 工单