How To Add Custom Rewrite Rules In WordPress

WordPress rewrite API used to convert URLs from something programmatically convenient to something user and search engine friendly. This article will give you some background information about WordPress URL rewriting principles and API.

What Is Rewriting?

URL rewriting is when you change what content is displayed by the server, normally when you type in a URL the web server will simply search for any files in that location. But with rewriting you can still show the same URL but in the back-end change where the server will look for the content. Therefore we can have a URL of /website-1 but tell the server to display content that is located in /website-1/content/index.php

How WordPress Uses Rewrite For Custom URLs?

When you go to Settings -> Permalinks, you will need to select how you want your URLs to appear on WordPress. You have many different options to choose from the default WordPress will use is ?p={post_id}, this is the value that is stored in the wp_posts table and what the rewrite API will write to, when it wants to display the post data.

When you select a new permalink structure WordPress will store these rules in the wp_options table so it will know how to search the post table for the correct post. This means that we can have URLs with just the post title in them and WordPress will know that it needs to search on the post_name column to find the correct post to display.

WordPress Rewrite API

Imagine you need to integrate custom page in which you can list your products. How can we do this?..First we need to create a new rewrite rule so wordpress can translate to We can use add_rewrite_rule() function which accepts 3 parameters. The first parameter is the URL pattern. The second parameter is the URL replacement and the third parameter is the priority. Let’s explore how to create this rule.

Catching the query variables

Using with plugin Activation and Deactivation

Copy Blog 🙂