Using WordPress ‘add_rewrite_rule()’ PHP function

The add_rewrite_rule() WordPress PHP function adds a rewrite rule that transforms a URL structure into a set of query variables. This function can be used to create more human-readable URLs or customize the URL structure of your WordPress site.

Usage

Here’s a basic usage of the add_rewrite_rule() function:

add_action('init', function() {
    add_rewrite_rule('products/([0-9]+)/?', 'index.php?post_type=product&p=$matches[1]', 'top');
});

This example allows you to create a URL like www.yourwebsite.com/products/123/, which will display the product post with the ID of 123.

Parameters

  • $regex (string) – Regular expression to match the request against.
  • $query (string|array) – The corresponding query variables for this rewrite rule.
  • $after (string) – Optional. Priority of the new rule. Accepts ‘top’ or ‘bottom’. Default is ‘bottom’.

More information

See WordPress Developer Resources: add_rewrite_rule()
Remember to always flush and regenerate the rewrite rules database after modifying rules.

Examples

Custom Post Type URL

The following code allows you to access a custom post type using a URL of the format www.yourwebsite.com/product/123/.

add_action('init', function() {
    add_rewrite_rule('product/([0-9]+)/?', 'index.php?post_type=product&p=$matches[1]', 'top');
});

Custom Page URL

This code lets you access a specific page with a URL of the format www.yourwebsite.com/page/123/.

add_action('init', function() {
    add_rewrite_rule('page/([0-9]+)/?', 'index.php?page_id=$matches[1]', 'top');
});

Custom Category URL

The following code allows you to display a specific category with a URL of the format www.yourwebsite.com/category/my-category/.

add_action('init', function() {
    add_rewrite_rule('category/([^/]+)/?', 'index.php?category_name=$matches[1]', 'top');
});

Custom Author URL

This code lets you access an author’s posts with a URL of the format www.yourwebsite.com/author/johndoe/.

add_action('init', function() {
    add_rewrite_rule('author/([^/]+)/?', 'index.php?author_name=$matches[1]', 'top');
});

Custom Tag URL

The following code allows you to access posts associated with a specific tag with a URL of the format www.yourwebsite.com/tag/my-tag/.

add_action('init', function() {
    add_rewrite_rule('tag/([^/]+)/?', 'index.php?tag=$matches[1]', 'top');
});

All these examples assume that the URLs do not conflict with existing WordPress URL structures or with each other. The add_rewrite_rule() function must be called on the init hook, which runs after WordPress has finished loading but before any headers are sent.