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.
Description Description
Any value in the $after parameter that isn’t ‘bottom’ will result in the rule being placed at the top of the rewrite rules.
Parameters Parameters
- $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'
Source Source
File: wp-includes/rewrite.php
function add_rewrite_rule( $regex, $query, $after = 'bottom' ) { global $wp_rewrite; $wp_rewrite->add_rule( $regex, $query, $after ); }
Expand full source code Collapse full source code View on Trac
Changelog Changelog
Version | Description |
---|---|
4.4.0 | Array support was added to the $query parameter. |
2.1.0 | Introduced. |
User Contributed Notes User Contributed Notes
You must log in before being able to contribute a note or feedback.
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.
A quick example: processing rules to make a subscribers page, hoping it helps.
Expand full source codeCollapse full source code
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:Example to add rewrite rule query as optional,hope it helps.
The main things here is to add ? in the start of your regex. Like
?([^/]*)
Now, you can set default value for optional query where you will use the query.
Now you will get the same result for
http://example.com/nutrition/strawberry
orhttp://example.com/nutrition/