^ 回到顶部
  • 人生没有定律,每个人都有自己的节奏
  • 本站wordpress建站教程均通过实践后发布,希望对你有帮助
  • 希望你的坚持,都是因为热爱,而不是因为不甘心
  • 5年wordpress建站经验,5星服务品质
  • 那些不愿意让你吃亏的人,才是真正值得你深交的人,也是值得你付出时间的人
  • 阿里云1核2g仅需102元/年,今日10点开抢

wordpress函数add_rewrite_rule()用法示例

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

Adds a rewrite rule that transforms a URL structure to a set of query vars.


描述

Any value in the $after parameter that isn’t ‘bottom’ will result in the rule being placed at the top of the rewrite rules.


参数

$regex

(string)
(Required)
Regular expression to match request against.

$query

(string|array)
(Required)
The corresponding query vars for this rewrite rule.

$after

(string)
(Optional)
Priority of the new rule. Accepts ‘top’ or ‘bottom’.

Default value: ‘bottom’


源代码

File: wp-includes/rewrite.php

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

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

更新日志

Version 描述
4.4.0 Array support was added to the $query parameter.
2.1.0 Introduced.

相关函数

Uses

  • wp-includes/class-wp-rewrite.php:
    WP_Rewrite::add_rule()

Used By

  • wp-includes/class-wp-post-type.php:
    WP_Post_Type::add_rewrite_rules()
  • wp-includes/rest-api.php:
    rest_api_register_rewrites()

User Contributed Notes

  1. Skip to note content

    You must log in to vote on the helpfulness of this noteVote results for this note: 1You must log in to vote on the helpfulness of this note

    Contributed by Samuel Elh

    A quick example: processing rules to make a subscribers page, hoping it helps.

    
    add_action('init', function() {
    
    	$page_id = 2; // update 2 (sample page) to your custom page ID where you can get the subscriber(s) data later
    	$page_data = get_post( $page_id );
    
    	if( ! is_object($page_data) ) { // post not there
    		return;
    	}
    
    	add_rewrite_rule(
    		$page_data->post_name . '/subscriber/([^/]+)/?$',
    		'index.php?pagename=' . $page_data->post_name . '&my_subscribers=1&my_subscriber=$matches[1]',
    		'top'
    	);
    
    });
    

    Now in your page template ( if you have one, or while filtering this custom page’s content ), you can get the displayed subscriber slug by calling get_query_var('my_subscriber'), but first, pass 'my_subscriber' to the query variables:

    
    add_filter('query_vars', function($vars) {
        $vars[] = "my_subscriber";
        return $vars;
    });
    
  2. Things that were in WP Codex site and did not get migrated for whatever reason.

    NOTE: When using $matches[] to retrieve the values of a matched URL, capture group data starts at 1, not 0.

    IMPORTANT: Do not forget to flush and regenerate the rewrite rules database after modifying rules. From WordPress Administration Screens, Select Settings -> Permalinks and just click Save Changes without any changes.

让小雨知道,这篇文章帮到了你
扫码关注微信公众号zs40086(微搜片)随时随地微信看片,抢先福利电影等你来

热门推荐

如有疑问,请前往问答中心反馈!

反馈