Back to Top

How to add new URL rewrite rule in WordPress?

To add new URL rewrite rule in Wordpress

Nowadays URL rewriting is most important for any kind of website. URL rewriting is to create a search engine friendly urls. URL rewrite means to remove ? and & from url query string and make it pretty.

WordPress provide permalink setting to use search engine friendly urls. Also,Wordpress stores rewrite rules into the options table of the database. But sometimes you want to add new rewrite urls which is not exists.

First of all,enable the permalink setting to default from wordpress admin panel and write following code into your htaccess.

# BEGIN WordPress

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress

You can add rewrite url using add_rewrite_rule() function in WordPress.The function allows three parameters. First parameter is the regex that will match with the rule and the second parameter is the rewritten URL whereas the third is used to define that where to place the rule at the top or bottom in database option.

Let’s look into the function:

function add_rewrite_urls() {
    add_rewrite_tag( '%YourNewVariable%', '([^/]*)' );
    $get_rewrite_rules = get_option( 'rewrite_rules' );
    $reg_exp = '^([^/]*)/([^/]*)/?';
    // check if the rule exists
    if ( !isset( $get_rewrite_rules[$reg_exp] ) ) {
register_activation_hook( __FILE__, 'add_rewrite_urls' );
add_action( 'init', 'add_rewrite_urls' );

You can access variable on page using get_query_var function like shown as below:

$variable = get_query_var( 'YourNewVariable' );

Add above code into your theme’s functions.php file or your plugin’s main file.This code will create new tag and rule for you.And flush_rewrite_rules() function will completely refresh the rewrite rules and fix if any problems with redirection.

So,We are done here. Add rule when require and enjoy 🙂
If you have any query or question,tell us in the comment section :). Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

How to Use PHP CodeSniffer?

Posted on 2 years ago


How to add Tags in WordPress Pages?

Posted on 6 years ago


Hello world

Updated 1 month ago

Nick Carter

In depth Understanding of Laravel Core

Updated 3 months ago


ECMAScript 6 New Features – 2

Updated 1 year ago


The Reader’s Poll – June 2015

Posted on 4 years ago


The Reader’s Poll – August 2014

Posted on 5 years ago


The Reader’s Poll – June 2014

Posted on 5 years ago


The Readers’ Poll – May 2014

Posted on 5 years ago


The Readers’ Poll – August 2013

Posted on 6 years ago