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.
Contents
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
-
$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'bottom'
.Default:
'bottom'
More Information
add_rewrite_rule() allows you to specify additional rewrite rules for WordPress. It is most commonly used in conjunction with add_rewrite_tag() (which allows WordPress to recognize custom post/get variables).
Source
File: wp-includes/rewrite.php
.
View all references
function add_rewrite_rule( $regex, $query, $after = 'bottom' ) {
global $wp_rewrite;
$wp_rewrite->add_rule( $regex, $query, $after );
}
Changelog
Version | Description |
---|---|
4.4.0 | Array support was added to the $query parameter. |
2.1.0 | Introduced. |
User Contributed Notes
You must log in before being able to contribute a note or feedback.
Here is a simple example of how to register a new rewrite rule, and pass it off to a PHP file for rendering:
1. Setup a rule:
2. Flush permalinks. Go to WP Admin > Settings > Permalinks > Save. This doesn’t happen automatically after you add this code
3. Whitelist the query param:
4. Add a handler to send it off to a template file:
Top ↑
Feedback
I added a modification for #4 to fix the 404 page issue.
add_action( 'template_include', function( $template ) { if ( get_query_var( 'myparamname' ) == false || get_query_var( 'myparamname' ) == '' ) { return $template; } if ( is_404() ) { status_header( 404 ); get_template_part( 404 ); exit(); } return get_template_directory() . '/template-name.php'; } );
— By signmein —
When defining the RegExp (step 1), I had to change
index.php?myparamname=$matches[1]
toindex.php?myparamname=$1
, otherwise it was not working properly. — By elcondorito —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.
Top ↑
Feedback
When adding multiple rules, note that (as of 4.9.8) rules are applied in the order added, regardless of whether they’re at the top or the bottom E.g.:
The second rule will never match, because the first rule always matches before the second one is processed. — By jbeninger —
A quick example: processing rules to make a subscribers page, hoping it helps.
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:Top ↑
Feedback
I’ll leave feedback here because you use
->post_name
column. I recommend that anyone who will try to use the code above, make sure to wrappost_name
withrawurldecode()
insideregex
argument. For example:add_rewrite_rule(rawurldecode($page_data->post_name), 'bla', 'top');
. In many case if yourpost_name
or known as URL slug is in English using pattern withoutrawurldecode()
works fine. But whenever yourpost_name
is in some other language like Thai, the character ค will be %E0%B8%84 when user type from address bar but inside WordPress DB it is %e0%b8%84. It is different case, yes! but that may lead you to 404 page while you are still confuse that all the characters you type is correct. Wrappost_name
withrawurldecode()
will be fine and works well. — By vee —(From Codex)
Using Custom Templates with custom querystring
Let’s assume you are creating a “Nutrition” page for showing nutritional information. This page uses a custom template and takes two variables, food and variety. Create a file named my-custom-template.php in your themes root directory as following:
Using this template, create a page. In Add New of Pages screen, select “Nutritional Information” from Template dropdown box. You may leave blank for title or contents. Click Publish to publish the page. Write down the ID of created page from All Pages screen. Move a mouse cursor on the page title to show the link information in status bar of Web browser. You will see the ID after the POST= in URL. In this example, assume the ID is 12.
Use add_rewrite_tag() to make WordPress aware of custom querystring variables food and variety. Add the following code to the functions.php file,
You can call the page as following:
http://example.com/index.php?page_id=12&food=milkshake&variety=strawberry
The page will show two values passed by querystring variables.
Now, instead of passing ugly querystring variables to the page, you can set up a rewrite rule to create some custom pretty URLs. Add the following rule to the functions.php file and replace the page ID 12 by the ID that you investigated in above step. Don’t forget to click Save Changes in Permalinks Settings. (refer above IMPORTANT)
User can access the same page with following URL:
http://example.com/nutrition/milkshakes/strawberry/
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/
Top ↑
Feedback
I am very confused on why the /?([^/]*)/? is necessary. If you can explain it, that will be great. * means 0 or more, but if you change it to + (1 or more) it fails to match. Why have the /? when the forward slash is necessary? The ? means 1 or 0. I removed ? and it (url matching) failed. — By wtlwp —
(From Codex)
Using rewrite rules to redirect to scripts other than index.php
The $redirect argument works slightly differently when redirecting to a custom PHP script because WordPress delegates these redirects to .htaccess instead of processing them itself. For this reason, querystring variables should be written like $1 instead of $matches[1]. Given we’re redirecting to a custom PHP script, adding the same rewrite rule from our previous example would look like this:
Rewrite rules with optional parameters.
Filters the query variables allowed before processing.
Retrieve query parameters values
(From Codex)
Basic Usage
You can retrieve any page by specifying ID in URL as following:
http://example.com/?p=95
If you add the following rule to the functions.php file, you can provide custom formed URL to access.
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.
Now, you can access the same page as
http://example.com/leaf/95
If you are distributing this in a plugin or theme, you may want to build in flushing rewrite rules. You can actually check to see if it has been set before you
flush_rewrite_rules();
using therewrite_rules
option.This option is autoloaded, so there is no extra database call.
Here’s a snippet:
If you need to keep custom taxonomy and post type using same slug, there is a way to use add_rewrite_rule for doing that. A simple case:
Example:
Remember to flush permalinks (Settings / Permalinks) once to apply changes.