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.
1 2 3 4 5 6 7 8 9 10 11 12 | # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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] ) ) { add_rewrite_rule( $reg_exp, 'index.php?pagename=$matches[1]&YourNewVariable=$matches[2]', 'top' ); flush_rewrite_rules(); } } 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:
1 2 3 | $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.