Wordpress Plugin: BWB-ReWriter for Custom URL Rewriting

Posted on Sunday, June 8th, 2008. Filed under Wordpress.

This plugin isn’t intended to revolutionize the world, but it does solve a problem that some of you may have. BWB-ReWriter is a small helper plugin to let you easily add parameters to your “pretty urls” in your Wordpress app. A big thanks to Gamerz and Zoom4 in this WP support topic for their info on how to make this work.

Download the plugin: BWB-ReWriter

What BWB-ReWriter does

For starters, this is version 0.1. In my case, that means that it works, it gets the job done, but you’ve got to open the code to add your own url’s.

BWB-ReWriter takes care of the necessary steps to let you add “pretty” parameters to your Wordpress urls. This may be particularly needed if you’re using Wordpress as a CMS. You may ask, “Why can’t I just add my rewrite rules to the .htaccess file?” The short answer is that Wordpress obliterates them, as far as I can tell, and I may be wrong…I’m running 2.5.1. So, you have to do it the WP way. Here are the steps that BWB-ReWrite takes to make that happen:

  1. Flush rewrite rules so WP will recalculate them and pick up your new rules
  2. Add your custom rules to the $wp_rewrite->rules array. It adds your rules to the top. Mod Rewrite takes rules in sequence, so if a standard Wordpress rule matches first, your rules will never be testing/applied.
  3. Add your parameters to the $public_query_vars[] array.

Add Your Custom Mod ReWrite Rules to the Wordpress rules engine

Wordpress has an object, $WP_Rewrite, that gets instantiated as $wp_rewrite by Wordpress, and is free for you to use. There appear to be different ways of interacting with that object to customize your urls. So, the code below is probably just one way to get ‘r done. Here is the salient code from the plugin, along with the comments that walk you through what you need to change to add your urls:

/*	Add your custom rules in the array below...the first part (the key,
	to left of =>) is the regular expression to match, the second part
	is the new value
*/
function bwb_add_rewrite_rules( $wp_rewrite )
{

	/*  Unsurprisingly by its name, this array contains your new rules.
		The array uses your Regular Expressions (the expressions test the raw
		URL for matches) as the keys.  The values (the string to the right
		of the "=>") are the new URLs.  In the function below, you will add
		your parameter names to $public_query_vars[].
		Separate Key + Value pairs with a comma.  Do not put a comma after
		the last pair...that always gets me b/c I copy/paste a lot.

		Change the page (regions) to your page name, change/add/remove
		variables and their corresponding regex matches "(.+)" to match
		your needs
	*/	

	$new_rules = array(
		'regions/(.*)/(.*)/(.*)' => 'index.php?page_id=4 ®ion='.
		$wp_rewrite->preg_index(1).'&country='.
		$wp_rewrite->preg_index(2).'&state='.
		$wp_rewrite->preg_index(3),
		'travel/(.*)/(.*)/(.*)' => 'index.php?page_id=4&country='.
		$wp_rewrite->preg_index(1).' ®ion='.
		$wp_rewrite->preg_index(2).
		'&state='.$wp_rewrite->preg_index(3)
	);

	//Add the rules to the rules array..wanna add them to the TOP, like so
	$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}

function bwb_query_vars($public_query_vars) {
	/*	ADD YOUR PARAMETERS or QUERY VARIABLES BELOW
		Uncomment the lines and change the variable names to the ones
		you want to use. Add more lines as needed
	*/

	$public_query_vars[] = "region";
	$public_query_vars[] = "country";
	$public_query_vars[] = "state";

	/*	Note: you do not want to add a variable multiple times.  As in
		the example above, multiple rules can use the same variables
	*/

	return $public_query_vars;
}

Using the Query Variables in your Code

I almost forgot to tell you…now that you’ve got the URLs working, to get the query variable values, all you need to do is something like this:

$region = get_query_var(’region’);
$country = get_query_var(’country’);
$state = get_query_var(’state’);

You’re all set.

Next Steps

Clearly, there is room for improvement here. I would like to add an options page that lets you type in your Match expressions, resultant values, and your variable names, and the plugin would pull these out of the database on the fly. That should work, and I intend on trying it. But here’s to version 0.1 ;-)

That’s about it. Hope it helps somebody out there!
Cheers,
Byron

Share and Enjoy:
  • Digg
  • del.icio.us
  • Slashdot
  • SphereIt
  • StumbleUpon
  • Technorati
  • YahooMyWeb
  • Google
  • Live
Sphere: Related Content



You can now:

Read Comments (9). Or, Leave A Trackback. Or, view Comments Feed.

Related Reading:

9 Responses to “Wordpress Plugin: BWB-ReWriter for Custom URL Rewriting

  • 1
    John D Wells
    July 10th, 2008 03:46

    THANK YOU. This topic is so poorly documented, it’s been a nightmare trying to sort this out.

    I have a question though, your plugin was the first code solution I’ve seen to place the new rules at the top of the rewrite chain, and indeed that’s the only way it works - place them at the end, and they don’t seem to take effect.

    Any idea why?

  • 2
    byron
    July 10th, 2008 12:04

    Hi John,

    I’m so glad someone found this useful. I guess it’s not a very popular topic (either that or it is so self-evident that everyone else gets it but me ;-) ).

    On your question, I am not really sure why it works like that, but my guess is that at some point in Wordpress’ processing it locks in the rewrite rules and you’re done.

    Let me share some more of my ignorance…I don’t know whether Wordpress is generating rewrite rules that get passed through Apache’s mod rewrite engine, or if Wordpress simulates what Apache does. If it is the former, then it would make sense that the rewrite rules would have to occur fairly early in the process since Apache does its .htaccess stuff very early on. I don’t see how Wordpress would be able to change those settings without generating some sort of redirect back through Apache’s process, but I really have no idea. Sorry…

    Cheers!
    Byron

  • 3
    John D Wells
    July 10th, 2008 13:30

    Hey Byron,

    I don’t know if it’s an unpopular topic, or if it’s just bloody impossible to find informative resources on the topic. But yours was only one of a few that I managed to find. And yours was the first that worked! :)

    Regarding your theory on how it works with Apache, your latter theory is correct - it simulates mod_rewrite. The .htaccess file that WP generates for pretty URLs is the giveaway - the standard setup has Apache route any requests that are not an actual file or directory (essentially a 404), and then WP uses its rewrite rules, which are as I can identical to how they’d be written in .htaccess, to finish routing the request.

    I’m willing to bet that you could take the exact same regexp patterns found in $wp_rewrite->rules, build up an .htaccess file, turn off pretty URLs in Wordpress, and the pretty URLs would still work.

    Of course none of this confident postulation means I actually know what to do with such information! At this point the online documentation is of little value to me - now I’m just scouring the source code itself and following the function trail.

    Anyway after your solution, I now need to figure out how to hijack the get_permalink() function and have it output the custom URLs that I’ve set up. Maybe I can return the favour…

    Cheers

  • 4
    byron
    July 10th, 2008 16:05

    John,

    Thanks for the insight into WP’s Apache interactions. I tried fooling around writing my own mod_rewrite rules in .htaccess. It was a miserably frustrating experience. So, I totally hear you on the lack of info on this subject. I beat my head on the wall for several hours trying to get something to work. Once I did, I had to capture it for posterity.

    For your get_permalink() dilemma, I just rolled my own on that, basically using one of the site url function/variables (like ABSPATH or site url depending on what I needed) and adding in the variables that I captured from my pretty urls.

    On another topic that I dealing with in WP, I don’t suppose you would have or know of any code that would let you make an AJAX call and get the logged-in user’s data…without including wp-config.php? I’m working on a little projec that will be making lots of little AJAX calls to the server and I need to get the logged-in user’s user ID in a relatively secure fashion. But including wp-config brings in the whole entire Wordpress application. Way, way, way!!! more overhead than I need for this. I’m using the Active Record classes from Code Igniter to do my database interatctions, so I don’t even really need WPDB.

    So far, the best that I’ve been able to do is to carve up wp-config and wp-settings and get rid of about 50-60% of the includes. Really unscientific method for doing that. I’d comment out the include if it didn’t break getting me the user ID, I left it out…if it did, I stuck it back in.

    This is not a great long term solution since I will want to keep the site upgraded to the latest stable versions of WP. I’d really like some good clean safe code that be able to do that into the future.

    Just thought I’d ask. I posted a question in the WP plugins/hacks forum, but not nary a response….again I have a knack for finding the unpopular topics :-)

    Good luck with your app!
    Byron

  • 5
    byron
    July 10th, 2008 16:24

    Hey, John.

    (I tried posting this comment on your site, but couldn’t get it to take an email address…wouldn’t let me post).

    I popped by to check out your site after you came by here for the Wordpress URL Rewrite plugin. I saw you raving about Things (which looks quite awesome, I might add). My questions to you in the comment above around getting Wordpress logged-in user data on AJAX calls without using wp-config are related to a To-do list app that I want to port from my home grown code to reside in Wordpress.

    Since you’re using Things and their iPhone port, you probably wouldn’t be interested in switching to my humble little app (SugarDo.com), but I’d love for you to check it out and let me know what you think. The main thing mine does that most of the others don’t is gives you hierarchical lists (hover over the menu box at the end of an item and select Add Sub-item).

    There are a boat load of features I want to add in my next iteration, such as dragging items from one level of the hierarchy to another, but I do have a few loyal users who have tried the other stuff out there and now swear by SugardDo.

    If you get a chance, create an account and check it out. Would love to hear from you on it.

    Cheers!
    Byron

  • 6
    John D Wells
    July 11th, 2008 07:57

    Strange that my site wouldn’t let you comment. I wonder if Disqus just had a glitch or something…

    Unfortnately I haven’t done anything with WP’s AJAX API, so I can’t help you on that one. Any tutorials I see always seem to start off by including wp-config.php. What is held in the session variable, anything that might be of use?

    I’ll give SugarDo.com a run, sure thing. It’s a tough nut to crack, to do list managers. I’ll be keen to see how yours goes.

    BTW, I’ve already tried writing the custom permalinks more or less as you’d suggested, but then when “pretty URLs” is turned off, of course they no longer work. But I’ve got a filter hook ‘post_link’ that shows promise…

    Cheers

  • 7
    byron
    July 11th, 2008 09:19

    Cool. Thanks for dropping by!

    Byron

  • 8
    mike
    July 30th, 2008 14:12

    Byron,

    I was wondering if you’d be able to have a look at a bit of code for me I’m having trouble with. Think you’ve done exactly what I need in this plugin but to be fair I’m completely lost!

  • 9
    byron
    August 3rd, 2008 21:30

    Hey, mike,
    Sorry for the delay in replying. Sure…I’ll lend a hand if I can. Let me know what the end result you’re shooting for and I’ll see if I can help.

    Byron


Subscribe without commenting


Leave a Reply

Note: Any comments are permitted only because the site owner is letting you post, and any comments will be removed for any reason at the absolute discretion of the site owner.

You must be logged in to post a comment.