Check Your Internet Speed

Rewriting URLs in WordPress Plugins

The newest updates to WordPress have allowed for developers to customize their personal website very quickly. It’s simple to update areas of your theme, replace widgets in the sidebar, and even write your own custom PHP code functions. The expanse is huge – and one area of popularity is rewriting pretty URL permalinks.
There are a few methods you can use to go about updating the default WordPress rewrite system. In this tutorial I will share a few examples and demonstrate how simple the process can be. You will need some understanding of PHP to follow what’s going on in the code, but it’s so easy to copy and paste into your own template, there’s practically no work involved.

Understanding WP_Rewrite

If you are at all familiar with mod_rewrite on Apache servers then you’ll pick up on the WordPress rewrite syntax. Their system is still built on top of an .htaccess file, but all the rules are coded in PHP. This actually makes the process a bit easier since we have more control over writing our own URLs.
I recommend skimming the $wp_rewrite class page as it has tons of info on the subject. There are even small examples we can reference to make everything easier to understand. Most of the code can be written directly into your theme’s functions.php file. Let’s start by looking at the default rewrites already included with WordPress.

Content of $wp_rewrite->rules

By declaring the $wp_rewrite class as global we have access to all of the internal data. When you go to append your own rules these are added into an array with the name $wp_rewrite->rules. It’s important to remember this variable since you’ll likely need to reference the data many times during development.
  1. <div><code>  
  2. <?php  
  3. global $wp_rewrite;  
  4. print_r($wp_rewrite->rules);  
  5. ?>  
  6. </code></div>  
I added this block of code into my theme’s page.php file. It will output a large array of data which looks like a big mess. But if you View Source on your page it’s actually easy to see which rewrite rules are matched to which filename. For example, let’s look at the rules for category rewrites:
  1. [category/(.+?)/?$] => index.php?category_name=$matches[1]  
The bit on the left side in brackets is our Apache RewriteRule to look for. Starting with the section /category/ followed by any string of characters. If this is matched then the server knows to reference index.php?category_name= while replacing the variable on the end.

Setting Custom Permalinks

There is so much content to go over in the $wp_rewrite class alone. Many other properties can be referenced, such as $wp_rewrite->category_base or $wp_rewrite->author_base for pulling the default URL structures for these pages. But aside from pulling WP’s default settings we can also build our own rules.

Rebuilding the Author Base

When you enter the Permalinks settings page you have the option of resetting category and tags bases. However the option to reset your author base is strangely missing.
But we can use the add_rewrite_rule() from WordPress’ codex to integrate some new settings. In this case I’ve replaced /author/ with /writer/ but you could use whatever base you like. Additionally I’ve copied some of the other redirects for author pages and RSS feeds. You can add this block of code into your theme’s functions.php file.
  1. add_action( 'init''add_author_rules' );  
  2. function add_author_rules() {   
  3.     add_rewrite_rule(  
  4.         "writer/([^/]+)/?",  
  5.         "index.php?author_name=$matches[1]",  
  6.         "top");  
  7.       
  8.     add_rewrite_rule(  
  9.     "writer/([^/]+)/page/?([0-9]{1,})/?",  
  10.     "index.php?author_name=$matches[1]&paged=$matches[2]",  
  11.     "top");  
  12.       
  13.     add_rewrite_rule(  
  14.     "writer/([^/]+)/(feed|rdf|rss|rss2|atom)/?",  
  15.     "index.php?author_name=$matches[1]&feed=$matches[2]",  
  16.     "top");  
  17.           
  18.     add_rewrite_rule(  
  19.     "writer/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?",  
  20.     "index.php?author_name=$matches[1]&feed=$matches[2]",  
  21.     "top");  
  22. }  
This function can be accessed even without using the $wp_rewrite variable. Some developers like this method because it’s simpler than hard-coding with class properties. However I’ve also noticed this method is not always reliable for some WordPress installations. There is actually a second option to add these rules on the hook after flushing your .htaccess (see below).

Author Base using generate_rewrite_rules

Writing for this method we will again need the global $wp_rewrite class. I’ve then setup a new variable named $new_rules which contains an associative array of data. My example code below just rewrites for the basic author page section.
  1. function generate_author_rewrite_rules() {  
  2.   global $wp_rewrite;  
  3.   $new_rules = array(  
  4.     "writer/([^/]+)/?" => "index.php?author_name=".$wp_rewrite->preg_index(1)  
  5.   );  
  6.   $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;  
  7. }  
But if we want to include multiple pages and RSS feeds we can beef up the array. You have the option of creating a PHP function to push associative array data which may be a bit too complex. We could also split the data blocks via commas, behaving as separate entities in the array. Check out my updated code again written in functions.php theme file.
  1. function generate_author_rewrite_rules() {  
  2.   global $wp_rewrite;  
  3.   $new_rules = array(  
  4.     "writer/([^/]+)/?" => "index.php?author_name=".$wp_rewrite->preg_index(1),  
  5.     "writer/([^/]+)/page/?([0-9]{1,})/?" => "index.php?author_name=".$wp_rewrite->preg_index(1)."&paged=".$wp_rewrite->preg_index(2),  
  6.     "writer/([^/]+)/(feed|rdf|rss|rss2|atom)/?" => "index.php?author_name=".$wp_rewrite->preg_index(1)."&feed=".$wp_rewrite->preg_index(2),  
  7.     "writer/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?" => "index.php?author_name=".$wp_rewrite->preg_index(1)."&feed=".$wp_rewrite->preg_index(2)  
  8.   );  
  9.   $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;  
  10. }  
Just remember that neither of these methods will work until after you’ve flushed the original rewrite rules. You will have to do this any time you make changes to these functions, but afterwards your new rules will stick indefinitely.

Flushing the Rewrite Rules

Whenever you make an update to the URL rewrite code, the changes are not applied immediately. You have to flush the .htaccess rewrite rules so your new code will be added. However performing this on every page init is extremely wasteful as it writes to the database and hard-refreshes the .htaccess file.
A better method is to access your permalinks page in the admin panel and re-save the changes. This always calls a flush_rewrite_rules so you never have to worry about users on the frontend experiencing loading troubles. And it only takes one time to re-save the page and update all the rules in your system. But if this doesn’t work you can try calling $wp_rewrite->flush_rules();

Using non-WP Rules

Inside the $wp_rewrite class we have access to dozens of properties. One of the more significant options is $wp_rewrite->non_wp_rules which collects an array of redirects which do not hit the index.php file.
This is actually used most often in WordPress plugin development. You can push a specific custom URL type (such as /calendar/june-2012/) into the backend of your website(/wp-content/plugins/calendarplug/myscript.php). But of course there are further uses for this associative array of custom rewrite rules other than plugins. I’ve provided an excellent example in the context below.

Source:hongkiat.com

0 comments:

Post a Comment

Websites Resources | Blogging | Technology News | Softwares - i Developments