add_rewrite_rule(): Add Custom URL Rewrite Rules in WordPress

add_rewrite_rule Description

add_rewrite_rule() lets us add custom rewrite rules to WordPress. It is usually used together with add_rewrite_tag(), which lets us add custom query parameters that WordPress can recognize.

add_rewrite_rule Usage

add_rewrite_rule($regex, $redirect, $after);

add_rewrite_rule Parameters

$regex

(string) (required) A regular expression used to match the requested URL. It can contain one or more capture groups.
Default: None

$redirect

(string) (required) The real URL that should be loaded when $regex matches. We can insert captured groups here by using the $matches[] array.
Default: None

$after

(string) (optional) This can be 'top' or 'bottom'. 'top' makes the rule run before WordPress’s existing rules, while 'bottom' handles it after the other rules.
Default: 'bottom'

add_rewrite_rule Example

Basic usage

First, we can easily get the ID of a page. By matching the page ID with a regular expression, we can define a custom URL for visiting that page.

add_action('init', function ()
{
    add_rewrite_rule('^leaf/([0-9]+)/?', 'index.php?page_id=$matches[1]', 'top');
});
When retrieving values from the matched URL, captured groups start at 1 rather than 0. After changing rewrite rules, do not forget to flush and rebuild the rewrite rules database. In the WordPress admin area, go to Settings -> Permalinks and click Save Changes directly.

Now we can access the same page through the following custom URL.

http://example.com/leaf/95

Use query strings in a custom template

Let us assume that you are creating a page called “Nutrition” to display nutritional information. This page uses a custom template and accepts two parameters: food and variety. Create a file named my-custom-template.php in your theme directory, and use the following content:

<?php
/**
* Template Name: Nutritional Information
*/
get_header();

global $wp_query;
echo 'Food : ' . $wp_query->query_vars['food'];
echo '<br />';
echo 'Variety : ' . $wp_query->query_vars['variety'];
// ... more ...
get_footer();
?>

Create a page with the template above and note the new page ID. Then use add_rewrite_tag() so WordPress can recognize the custom query variables food and variety. The example code is as follows:

add_action('init', function ()
{
    add_rewrite_tag('%food%', '([^&]+)');
    add_rewrite_tag('%variety%', '([^&]+)');
}, 10, 0);

When we visit the following page, the page receives two custom parameters through the query string.

http://example.com/index.php?page_id=12&food=milkshake&variety=strawberry

Now we can create a custom rule that rewrites the query string above into a static-looking URL. Add the following code to your theme or plugin, replacing 12 with the ID of the custom page we created above. After adding it, do not forget to save the permalink settings again so that the new custom rewrite rule takes effect.

add_action('init', function ()
{
    add_rewrite_rule('^nutrition/([^/]*)/([^/]*)/?', 'index.php?page_id=12&food=$matches[1]&variety=$matches[2]', 'top');
}, 10, 0);

After saving the permalink settings again, we can visit the rewritten custom page through the URL http://example.com/nutrition/milkshakes/strawberry/.

As you can see from the code above, adding custom URL rules can still be cumbersome. If you need to add many custom URLs, you can use the WordPress Dispatcher custom routing library to simplify the work.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *