Contents

Description

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).

Usage

<?php add_rewrite_rule($regex, $redirect, $after); ?>

Arguments

$regex

(string) (required) A regular expression to match against a requested URL. This can optionally use one or more capture groups.

Default: None

$redirect

(string) (required) The URL you would like to actually fetch (when the $regex is matched). You can use the $matches[] array to insert capture group matches here.

Default: None

$after

(string) (optional) This can either be 'top' or 'bottom'. 'top' will take precedence over WordPress's existing rules, where 'bottom' will check all other rules match first.

Default: "bottom"

Example

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.

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.

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)