WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Rewrite API/add rewrite rule

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

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. Instead of passing ugly querystring variables to the page, you can set up a rewrite rule to create some custom pretty URLs. See below...

add_rewrite_rule('^nutrition/([^/]*)/([^/]*)/?','index.php?page_id=12&food=$matches[1]&variety=$matches[2]','top');

This example would match a requested URL like this: example.com/nutrition/milkshakes/strawberry/ ...and interpret it to actually mean... example.com/index.php?page_id=12&food=milkshake&variety=strawberry

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

IMPORTANT: By default, WordPress will not recognize custom querystring variables used for rewrites. You must register your querystring variables with WordPress. Simply use add_rewrite_tag() to capture querystring variable values after a rewrite, or the above rewrite will not work!

Source File

add_rewrite_rule() is located in wp-includes/rewrite.php

Related

Articles

Hooks

Functions