1. Code
  2. Creative Coding

The Rewrite API: The Basics

Scroll to top
Read Time: 13 min

This is part one of a two part series looking at WordPress' Rewrite API. In this tutorial we look at how rewrites work and the basic methods available to create custom rewrite rules.

What Is Rewriting?

WordPress, like all content management systems, decides what content to display based on the variables (usually called query variables) passed to it. For instance: tells WordPress we are after posts in a category with an ID of 3 and tells WordPress we want the site's feed in RSS format.

Unfortunately this can leave us with rather ugly URLs:

This is where WordPress' rewriting steps in. It allows us to replace the above with:

Which is now not only much more readable (and memorable) but also more SEO friendly. This is, in a nutshell, what rewrites do.

How Does It Work?

Now doesn't exist as a directory or a file. So how does WordPress serve up the correct content? When WordPress receives a 'pretty permalink' like the above it needs to convert that into something it understands, namely a query object. More simply it has to take the pretty URL, and map the appropriate parts to the correct query variable. So for our example:

  • post_type is set to 'portfolio'
  • portfolio-taxonomy is set to 'wordpress'
  • portfolio is set to 'my-fancy-plugin' (the post name)

Then WordPress knows we are after posts of type 'portfolio', in the 'wordpress' 'portfolio-taxonomy' taxonomy term with name 'my-fancy-plugin'. (As you may have guessed the first two are actually redundant). WordPress then performs that query, chooses the appropriate template with which to display the results and then serves that to the viewer. But clearly WordPress doesn't just guess how to interpret the URLs, it needs to be told...

It Starts With .htaccess

Assuming you can and have enabled pretty permalinks on your Settings -> Permalinks page (see the Codex for minimum requirements – for WordPress on Nginx servers there is this plug-in) – then things start with the .htaccess file. It plays a simple and yet significant role. WordPress includes something similar to the the following in this file:

This simply checks if the file or directory actually exists – and if it does, you are simply taken there. For instance:

Would simply take you the PNG attachment 'my-picture.png'. But, as in the case of:

Where the directory does not exist – you are taken to your WordPress' index.php file. It's this file which boots WordPress.

Interpreting the URL

At this point, WordPress doesn't yet know what you're after. After some initial loading of WordPress and its settings, it fires the parse_request method of the WP class (located in the class-wp.php file). It's this method which takes the /portoflio/wordpress/my-fancy-plugin and converts it into a WordPress-understandable query object (almost, it actually sets the query_vars array and afterwards $wp->query_posts turns this into a query).

In short this function compares the received URL (/portoflio/wordpress/my-fancy-plugin) with an array of 'regular expressions'. This is the rewrite array – and it will look something like this:

The keys of this array are regular expressions, and the received URL is compared against each in turn until there is a match with the pattern of the URL received. The corresponding value, is how the URL is then interpreted. The $matches array contains the captured values (indexed from 1) from the matching.

For example, visiting, WordPress will look for the first pattern that matches 'tag/my-tag'. With the above array, it matches the third pattern: tag/([^/]+)/?$. This tells WordPress to interpret the URL as and correspondingly the 'my-tag' archive is served.

Of course, WordPress lets you customise this array, and the rest of this tutorial is dedicated to showing you how.

Customising the Rewrite Rules

Settings -> Permalinks

Your first port of call should be the 'Permalink' settings page. This page allows you to alter the rules for the default 'post' post type, and 'category' and 'tags' taxonomies. The 'default' option has pretty permalinks disabled, but you can select from a list of preset structures or create a custom structure. Please note that custom structures should not contain your site URL. WordPress allows you to alter your permalink structure by adding in provided tags such as %postname% (the post's name), %year% (the year the post was published) and %author% (the author of the post). A permalink structure such as:

Would produce a post link such as:

The documentation for these options can be found in the WordPress Codex. (Later on I'll be showing you how to create your own custom tags).

However, the provided options are quite limited. In this tutorial I shall focus on the functions provided by WordPress that offer greater control over permalink structures and how they are interpreted. I won't be covering the rewrite options available for custom post types or taxonomies, as this will be covered in part 2.

Why Flush the Rewrite Rules?

After any alteration to the rewrite rules (for example, by either using one of the following methods, or registering a custom post type or taxonomy) you may find that the new rules do not take effect. This is because you you need to flush the rewrite rules. This can be done either one of two ways:

  • Simply visit the Settings -> Permalink page
  • Call flush_rewrite_rules() (covered in part 2)

What does this do? Recall that the parse_request method compares the request against a rewrite array. This array lives in the database. Flushing the rewrite rules updates the database to reflect your changes – and until you do so, they won't be recognised. But parse_request also writes to the .htaccess file. This makes it an expensive operation. So, although I won't cover the use of flush_rewrite_rules() until part 2, I will give you this warning: Do not call flush_rewrite_rules on every page load. Plug-ins should only call this when the plug-in is activated and deactivated.

Add Rewrite Rule

The add_rewrite_rule allows you to add additional rules to the rewrite array. This function accepts three arguments:

  • rule – a regular expression with which to compare the request URL against
  • rewrite – the query string used to interpret the rule. The $matches array contains the captured matches and starts from index '1'.
  • position – 'top' or 'bottom'. Where to place the rule: at the top of the rewrite array or the bottom. WordPress scans from the top of the array to the bottom and stops as soon as it finds a match. In order for your rules to take precedence over existing rules you'll want to set this to 'top'. Default is 'bottom'.

Note: if you use add_rewrite_rule several times, each with position 'top' – the first call takes precedence over subsequent calls.

Let's suppose our posts have an event date associated with them and we want to have this structure: interpreted as then we can add this rule as follows:

The following would interpret as

If you're unsure of your regular expressions, you may find this introduction and this tool useful.

Add Rewrite Tag

You may think that the value of eventdate (2012-07-27 in the above example), olymyear and game may be accessible from WordPress' internals via the get_query_var (in the same way that get_query_var('paged') gets the page number you are on). However, WordPress does not automatically recognise the variable eventdate even though it's interpreted as a GET variable. There are a couple of ways to make WordPress recognise custom variables. One is to use the query_vars filter as demonstrated in the 'Add Custom Endpoint' section below. Alternatively, we can go a step further and use add_rewrite_tag to register a custom tag like the default %postname% and %year%

This function accepts three arguments:

  • tag name – (with leading and trailing %) e.g: %eventdate%
  • regex – Regular expression to validate the value, e.g. '([0-9]{4}-[0-9]{2}-[0-9]{2})'
  • query – (optional) How the tag is interpreted, e.g. 'eventdate='. If provided, must end with a '='.

Not only will get_query_var('eventdate') return the value of the date in the URL, but you can use the tag %eventdate% in the Settings -> Permalink (along with the default %year%, %postname% etc.) and WordPress will correctly interpret it. Unfortunately when generating a post's permalink, WordPress doesn't know how to replace %eventdate% with the appropriate value: so our post permalinks end up like:

We need to replace %eventdate% with an appropriate value, and we can do so using using the post_link filter. (In this example, I shall assume that the value is stored in a custom field 'eventdate').

In part 2 of this series I will cover custom tags for custom post types.

Add Custom Endpoint

Endpoints are tags which are appended to the URL (/trackback/[value] is the most common). It has several other potential uses: displaying different templates depending on the value set, custom notifications, and displaying posts in different 'formats' (printable, XML, JSON etc).

You can create endpoints with add_rewrite_endpoint. This function accepts two arguments:

  • name – The name of the endpoint e.g. 'json', 'form', etc.
  • where – Endpoint mask specifying where the endpoint should be added. This should be one of the EP_* constants listed below (or a combination using bitwise operators). When you register custom post types you can create a mask for that post type:

The default endpoint masks are:

  • EP_PERMALINK – for post permalinks
  • EP_ATTACHMENT – for attachments
  • EP_DATE – for date archives
  • EP_YEAR – for year archives
  • EP_MONTH – for month archives
  • EP_DAY – for 'day' archives
  • EP_ROOT – for the root of the site
  • EP_COMMENTS – for comments
  • EP_SEARCH – for searches
  • EP_CATEGORIES – for categories
  • EP_TAGS – for tags
  • EP_AUTHORS – for archive of author's posts
  • EP_PAGES – for pages
  • EP_ALL – for everything

End points are extremely flexible, you can use them with bitwise operators so, for example, you can add an endpoint to post and page permalinks with EP_PERMALINK | EP_PAGES.

As a brief example, endpoints can be useful for form submissions. Suppose we have a contact form page with name contact-form and with permalink: and want the the URLs:

  • – to reflect a successful form submission
  • – to reflect an unsuccessful form submission

This can be done with endpoints. The following is a very simple example of how to use endpoints, and so the form is incredibly basic in its checks (and in fact doesn't do anything with the data). Normally a form like this would work best in a plug-in, using shortcodes – but for the purposes of this example, create a page with the following template and the rest of the code you can put in your functions.php

(In case you are wondering, the honey is referring to this very basic method of catching spam outlined here. It's certainly not fool proof, but proper form processing and spam protection is off topic here). Now we create our endpoint:

Next we add our 'form' variable to the array of recognised variables:

Finally we provide a form handler, which will process the data, submit the form, and then redirect back to the contact page with the relevant endpoint value appended.

Of course even this example could be greatly improved by providing more detailed error messages that convey the reason for failure.

Adding a Custom Feed

With pretty permalinks enabled WordPress automatically produces pretty URLs for your site's feed: The add_feed function allows you to create a custom feed, which if pretty permalinks are enabled, will also have a 'pretty' URL. This function accepts two arguments:

  • feed name – The name of the feed as it will be appear in feed/[feed-name]
  • feed callback – The function responsible for displaying the feed contents.

The following is intended as an example of add_feed, and provides a very basic custom feed.

After flushing the permalinks, the feed will be available at

Checking the Rewrite Rules

Once you've added some of your own rewrite rules (and flushed them), you will probably want to check if they are working properly – and if they're not, find out what's going wrong. For this, I strongly recommended the Monkeyman Rewrite Analyzer plug-in, a free plug-in available in the WordPress repository. Once activated, this plug-in adds a page to your 'Tools' section, which lists all your rewrite rules.

You can also test the rules by giving it an example URL, and the plug-in will filter the rules to show only matching patterns and indicating how WordPress would interpret the URL.

Have fun, and keep an eye out for Part 2, coming soon!

Please note: There is a currently a bug in our syntax highlighter that displays "empty()" as "emptyempty()". Don't forget to adjust your code accordingly.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.