WordPress函数:add_rewrite_rule 添加一个重写规则

江河/ 01月23日/ WordPress/ 浏览 399

函数原型:


add_rewrite_rule( string $regex, string|array $query, string $after = ‘bottom’ )


添加一个重写规则,该规则将URL结构转换为一组查询变量。


$after参数中任何不是“bottom”的值都将导致该规则位于重写规则的顶部。


参数说明:


$regex 用于匹配请求的正则表达式


$query 此重写规则的相应查询变量


$after 优先级 'top' 或 'bottom',默认'bottom'


函数源码:


function add_rewrite_rule( $regex, $query, $after = 'bottom' ) {
	global $wp_rewrite;

	$wp_rewrite->add_rule( $regex, $query, $after );
}


使用举例:


1. 添加一个规则


add_action( 'init',  function() {
    add_rewrite_rule( 'myparamname/([a-z0-9-]+)[/]?$', 'index.php?myparamname=$matches[1]', 'top' );
} );


2. 在后台->设置->链接,点击保存。添加规则后,规则并不会立即生效,而是必须这样操作之后才行。


3. 将参数添加到白名单


add_filter( 'query_vars', function( $query_vars ) {
    $query_vars[] = 'myparamname';
    return $query_vars;
} );


4. 添加一个处理程序以将其发送到模板文件


add_filter( 'template_include', function( $template ) {
    if ( get_query_var( 'myparamname' ) == false || get_query_var( 'myparamname' ) == '' ) {
        return $template;
    }

    return get_template_directory() . '/template-name.php';
} );


发表评论

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

客服 工单