WordPress Plugin: BWB-ReWriter for Custom URL Rewriting

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

84 Responses to WordPress Plugin: BWB-ReWriter for Custom URL Rewriting

  1. John D Wells July 10, 2008 at 3:46 am #

    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 10, 2008 at 12:04 pm #

    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 10, 2008 at 1:30 pm #

    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 10, 2008 at 4:05 pm #

    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 10, 2008 at 4:24 pm #

    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 11, 2008 at 7:57 am #

    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 11, 2008 at 9:19 am #

    Cool. Thanks for dropping by!

    Byron

  8. mike July 30, 2008 at 2:12 pm #

    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 3, 2008 at 9:30 pm #

    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

  10. Soledad October 24, 2008 at 12:06 pm #

    How am I supposed to use this? All I know is that I want ?cat=id&region=sometext be converted to pretty_wp_category_permalink/in-sometext. Any help would be very much appreciated. Thanks in advance.

  11. Byron Bennett October 24, 2008 at 1:17 pm #

    Hi Soledad,

    for a url like: http://www.yoursite.com/category/my_category/my_text

    adjust the code in the plugin to (note…you probably shouldn’t use “category” if that is what you set up for your category word in Permalink Settings…probably should be something different:

    function bwb_add_rewrite_rules( $wp_rewrite )
    {

    $new_rules = array(
    ‘category/(.*)/(.*)/$’ => ‘index.php?cat=’.
    $wp_rewrite->preg_index(1).’&region=’.
    $wp_rewrite->preg_index(2),
    ‘category/(.*)/(.*)’ => ‘index.php?cat=’.
    $wp_rewrite->preg_index(1).’&region=’.
    $wp_rewrite->preg_index(2)
    );

    //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”;

    /* 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;
    }

  12. Soledad October 25, 2008 at 9:18 am #

    WOW! I don’t know what to say, really, you impressed me with such a fast and complete reply! Thank you so much!

    That said I can’t test the plugin right now but it’s the first thing I’ll do this monday. Anyway, I got lost in the new_rules array but now it seems I understand how the code works thanks to your reply (and to the three hours or so that I’ve spent reading about regular expressions -I guess I should have done this first… Sorry!).

    Again, thank you so much for the plugin and… for the extra time with me! It’s a pleasure to find people like you! Best wishes!

    PS: I let you know this monday if I could made the plugin work tha way I want.

  13. Byron Bennett October 25, 2008 at 12:45 pm #

    Soledad,
    You’re very welcome. I just hope it’ll work for you.

    Rewriting URLs in WordPress is not very well documented (at least that I could find/understand). That’s the reason I put this plugin together. After hours and hours of trying different routes, I got this plugin to work. So I feel your pain.

    These things can be finicky, so hopefully it’ll work. If not let me know and I’ll take another look at it.

    I find Regular Expressions very complicated. Once I got some that worked, I’ve stuck pretty close to those.

    Good luck!
    Byron

  14. Soledad October 28, 2008 at 3:42 am #

    Sorry to be one day late -yesterday I had to take care of my 3 years old daughter and in the end this modified all my plans, well, with babies those things happen more often than not 🙂 – but the good news is that I finally made the plugin work. Yes!

    Thank you so much for the code and your support (I hope your reply is of help to others). Well, I’m happy not only because I managed to modify the plugin to suit my needs but because thanks to all this I have also learnt a lot about regular expressions… they are complex! Oh, and I didn’t really knew how many things you can actually do with a simple htaccess file (I just knew about basic redirections, but there is really more to it).

    Once again, thank you so much for all your time! As I said, it’s a pleasure to meet people like you (with all the time you spend helping others, you make internet such a great place!). Best wishes!

  15. Byron Bennett October 28, 2008 at 7:37 am #

    Hi Soledada,
    I’m glad it worked! I must say that I was a little skeptical that it would. My experience with computers is that things rarely work the first time and it is just an incredible relief when they do.

    I hear you about babies…we have a 2 yr old who just had his tonsils out. His sleeping patterns are all messed up. And that pretty much upsets the whole house.

    Well, I’m glad this was helpful. I’ve been helped so much by other people on the web…I’m glad to finally have something to give back a little.

    Cheers!
    Byron

  16. wordpress4you December 3, 2008 at 5:38 am #

    Thanks. Your plug-in helped me understanding WordPress permalink rewriting concept a big time. Thanks!

  17. Colin December 9, 2008 at 8:13 am #

    Hi, great plugin.
    Although I’m having one problem…

    I can’t get the variables to display, i’m using your plugin almost exactly.. the pretty permalinks work but when i try to echo them using

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

    echo $region;
    echo $country;
    echo $state;

    I get no results… am i missing something?

    All the best

  18. Byron Bennett December 9, 2008 at 8:51 am #

    Hi Colin,

    What does your new rules array from the bwb_add_rewrite_rules function look like? Also, what is the URL you are using with these rules?

    Hopefully we can get to the bottom of this for you.

    Cheers!
    Byron

  19. Colin December 9, 2008 at 3:36 pm #

    G’day sorry about the slow reply (sleeping)
    Here they are.
    regions/(.*)/(.*)/(.*) == index.php?page_id=105&region=$matches[1]&country=$matches[2]&state=$matches[3]
    travel/(.*)/(.*)/(.*) == index.php?page_id=105&country=$matches[1]&region=$matches[2]&state=$matches[3]

    Many thanks

  20. Byron Bennett December 9, 2008 at 4:09 pm #

    Colin,

    Just to check a couple of easy things first, did you use => to separate the regions/(.*)… from the index.php?page_id….? You comment showed ==. So it should look like:

    regions/(.*)/(.*)/(.*)’ => ‘index.php?page_id=4 ®ion=’.
    $wp_rewrite->preg_index(1).’&country=’.
    $wp_rewrite->preg_index(2).’&state=’.
    $wp_rewrite->preg_index(3)

    And secondly, the url to access this would be something like:

    http://www.yoursite.com/regions/na/us/mo

    If you don’t have all of the segments, it won’t work. You’d have to add additional rules to handle url’s with more or less segments….also might try adding a rule that includes a trailing / on the regions piece.

    You’re probably doing those ok, but just checking some of the easy possibilities first.

    Byron

  21. Colin December 9, 2008 at 4:46 pm #

    Ah hold on sorry for the daft question but before we go any further…
    is ‘regions’ meant to be the page name? or is standalone?

  22. Colin December 9, 2008 at 5:04 pm #

    alright sorry for the barrage of comments, i’ve set your plugin back to default (nothing is changed except the page_id)
    I got to http://www.mysite.com/regions/na/us/mo
    It correctly displays the right page.

    In the page template I have

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

    echo $region;
    echo $country;
    echo $state;

    but they all are empty.

    The rewrite rules are set to
    regions/(.*)/(.*)/(.*) == index.php?page_id=105&region=$matches[1]&country=$matches[2]&state=$matches[3]
    travel/(.*)/(.*)/(.*) == index.php?page_id=105&country=$matches[1]&region=$matches[2]&state=$matches[3]

    (and i think the == is just how the rewriter ruler plugin display them)

  23. Byron Bennett December 9, 2008 at 5:53 pm #

    Colin,

    Here is the code straight out of the plugin file:

    $new_rules = array(
    ‘regions/(.*)/(.*)/(.*)’ => ‘index.php?page_id=4&region=’.
    $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).’&region=’.
    $wp_rewrite->preg_index(2).
    ‘&state=’.$wp_rewrite->preg_index(3)
    );

    The differences I see between what you’re showing and the plugin code are:
    1) == vs. => (PHP uses => to build arrays)
    2) $matches[#] vs. $wp_rewrite->preg_index(#)

    See if putting those back to the default helps. Let me know if not…we’ll get to the bottom fo this.

    BB

  24. Colin December 10, 2008 at 10:17 pm #

    Hey mate, it works now. i just wasn’t using the correct string to output them.

    Correct way for me is.
    $searchKey = $wp_query->query_vars[‘region’];
    echo $searchKey;

  25. Byron Bennett December 11, 2008 at 9:26 am #

    Colin,
    Excellent! I was spinning my wheels there.

    Cheers!
    Byron

  26. Karen December 11, 2008 at 12:53 pm #

    Thanks for sharing this plugin. I’m hoping I can get the plugin to do what I need. You’re assistance would be greatly appreciated.

    The simple permalinks on my site currently look like this:

    http://www.mysite.com/cars/?color=red&model=ford&year=2008
    http://www.mysite.com/trucks/?color=blue&model=ford&year=2008

    Both pages http://www.mysite.com/cars/ and http://www.mysite.com/trucks/ are just wordpress pages with php in the templates to process the parameter string.

    I would like the links to look like this:

    http://www.mysite.com/cars/red/ford/2008/
    http://www.mysite.com/trucks/blue/ford/2008/

    Using your plugin, I’ve tried something like the following:

    $new_rules = array(
    ‘cars/(.*)/(.*)/(.*)$’ => ‘/hype/?color=’.$wp_rewrite->preg_index(1).’&model=’.$wp_rewrite->preg_index(2).’&year=’.$wp_rewrite->preg_index(3),
    ‘trucks/(.*)/(.*)/(.*)$’ => ‘/hype/?color=’.$wp_rewrite->preg_index(1).’&model=’.$wp_rewrite->preg_index(2).’&year=’.$wp_rewrite->preg_index(3)
    );

    but this does not seem to work. Am i using the plugin wrong or did I mess up on the regular expressions?

  27. Karen December 11, 2008 at 12:56 pm #

    oops.. i mistyped the rule in that post and I don’t see an option to edit so I will repost the rule…

    $new_rules = array(
    ‘cars/(.*)/(.*)/(.*)$’ => ‘/cars/?color=’.$wp_rewrite->preg_index(1).’&model=’.$wp_rewrite->preg_index(2).’&year=’.$wp_rewrite->preg_index(3),
    ‘trucks/(.*)/(.*)/(.*)$’ => ‘/trucks/?color=’.$wp_rewrite->preg_index(1).’&model=’.$wp_rewrite->preg_index(2).’&year=’.$wp_rewrite->preg_index(3)
    );

    Sorry for the confusion

  28. Byron Bennett December 11, 2008 at 2:38 pm #

    Hi Karen,

    This might fix you up…go into your Admin/Pages and figure out what the ID #’s for the pages you’re hitting are. Then change your rules to something like:

    $new_rules = array(
    ‘cars/(.*)/(.*)/(.*)$’ => ‘index.php?page_id=4&color=’.$wp_rewrite->preg_index(1).’&model=’.$wp_rewrite->preg_index(2).’&year=’.$wp_rewrite->preg_index(3)

    The key change being the change from ‘/cars/?color=’ after the => to ‘index.php?page_id=4&color=’

    Hopefully that’ll do it. Let me know.

    Byron

  29. Byron Bennett December 11, 2008 at 2:39 pm #

    Karen,
    I might not have been clear. I put index.php?page_id=4. That page_id= needs to be whatever your desired page ID is. It will be different for each page. You might have to hover over the page link in Manage/Pages in Admin to see what the ID is in the URL.

    BB

  30. Karen December 11, 2008 at 3:01 pm #

    Thank you for the quick response. That worked! I appreciate your help.

    Karen

  31. Colin December 12, 2008 at 9:25 am #

    Byron, it’s amazing that you help everyone so quickly and with quality responses (for free!).
    Major props to you mate, I truely respect you.

    Thanks again for the plugin.

  32. Byron Bennett December 12, 2008 at 9:53 am #

    Thanks Colin…my pleasure.

    My turn to give back a little bit 🙂

    BB

  33. Lizy Buelle February 19, 2009 at 6:26 am #

    Keep up the good work. Look forward to reading more from you in the future. Subscribed to your RSS

  34. Steve Napierski March 4, 2009 at 7:59 am #

    I just want to say this plugin is awesome. I looked all over for someone who had done what you had accomplished but to no avail. You’d think with this SEO hungry world that something like this would be easy to find. Just glad you decided to write it.

  35. Byron Bennett March 4, 2009 at 8:08 am #

    Thanks, Steve.
    I hear you. I spent too much time hunting around for that information myself.
    BB

  36. Skwerl March 21, 2009 at 10:18 am #

    hey byron, this code worked beautifully for me. i can’t thank you enough. i’m with steve- you nailed it. great work.

  37. Navjot Singh April 24, 2009 at 2:52 pm #

    How will the code change if suppose instead of root index.php, I have a file named yshort.php residing in a template and I need to pass variables to this file and want to get it rewritten? Pls help in this case?

    I tried your method by even specifying the theme directory but it didn’t worked out.

  38. Byron Bennett April 24, 2009 at 3:07 pm #

    Hi Navjot,

    It should work if you add your rule, something like:

    $new_rules = array(
    ‘yourpage/(.*)/(.*)’ => ‘wp-content/themes/yshort.php?param1=’.
    $wp_rewrite->preg_index(1).’&param2=’.
    $wp_rewrite->preg_index(2) );

    And then add the parameters to the Query Vars array:

    $public_query_vars[] = “param1”;
    $public_query_vars[] = “param2”;

    Hopefully that will work.

    Byron

  39. Navjot Singh April 25, 2009 at 1:55 am #

    It didn’t work out that way. Even though the rewrite is mentioned when I used Rewrites Viewer Plugin by Dagon Design where wordpress listed the rewrite query as:

    [videos/(.*)/(.*)/(.*)] => wp-content/themes/Videographer/yshortdown.php?yid=$matches[1]&yfn=$matches[2]&qua=$matches[3]

    But it does not get rewritten. Seems another solution is needed. Thanks for help!

  40. EngineHere April 27, 2009 at 7:02 am #

    Thanks for this code !
    It took me a while to understand that adding rules to .htaccess won’t do the trick.

    Perhaps I’ve missed something in your post, but at least in my case, your code alone wasn’t enough to make it work:
    I had to add Zoom4’s suggestion to hook to ‘init’ and do $wp_rewrite->flush_rules()

  41. Mårten May 14, 2009 at 8:56 am #

    Thank you, this is so helpful.

  42. Aaron June 1, 2009 at 1:01 pm #

    Your the man!

  43. Karl Jones June 4, 2009 at 9:47 am #

    Hi Byron,

    Thanks for shedding much-needed light on WP Rewrite. Excellent post and followup comments: you’ve done the WordPress community (and me personally) an important service here.

    I’m sure that your approach relates to a problem I’m trying to solve: “virtual pages”. Maybe my problem is a variation on your solution, or maybe I’m just not grasping your solution. Say I have a URL like this:

    http://some-site.com/members/

    “members” is the slug for a WordPress page with its own dedicated template (with associated plugin). The template serves as a “virtual parent page” by handling querystring elements at the template/plugin level. The virtual children result from querystring handling rules in the template. There will be no real child pages of “members”.

    In other words: the “members” template gets to handle the querystring, overriding WordPress.

    Example:

    http://some-site.com/members/29/profile
    http://some-site.com/members/29/inbox

    The “members” template decides that “29” is a valid user_ID, and “profile” (or “inbox”) is a valid token indicating content format. Template makes the appropriate $wpdb calls, generates the content. Or maybe “28” isn’t a valid user, or “asdf” isn’t a valid token, so the code does its own 404 handling, overriding WP.

    Thanks in advance for any advice. And thanks again for the informative post.

    – Karl Jones

    PS, an observation: what we have here is a URL generator. WordPress and Drupal and CodeIgniter and all the other web-based content management systems — URL generators, engines for generating URLs. Sure, “content is king” … it’s the blog post that people read, not the URL … but I’m URL-centric … the URL generator is heart of the matter.

  44. Byron Bennett June 4, 2009 at 1:34 pm #

    Hi Karl,

    Yes, BWB-Rewriter directly addresses your issue. You have 3 elements: members, 29, and profile (or inbox). With the members element, you would determine what the page ID you want to send the code to. With 29 and profile, you would assign them to variables that you can use in your code to have the page do different things (like show a profile or an inbox).

    So your rule could look something like the following…the ‘4’ in page_id=4 needs to be the numeric page ID for the WP Page that represents your members template. If you don’t already have one, you’ll need to create a page for that so you can use the regular WP stuff to reference it. Here’s an example rule:

    ‘members/(.*)/(.*)/(.*)’ => ‘index.php?page_id=4&userid=’.
    $wp_rewrite->preg_index(1).’&action=’.
    $wp_rewrite->preg_index(2)

    so: members/29/profile would eqaul: page_id=4&userid=29&action=inbox

    do the wp query vars thing and then you get sent to the page with your code and you have the userid and action variable available to use.

    Hope that helps.

    Byron

  45. Fastele June 10, 2009 at 5:43 pm #

    Hi Byron,
    I have read your piece and followed the comments and I think you are the person who can help. I am new to WordPress. I am trying to able to modify the labels on pages to some other language via a script that I have created which holds the translated text. The idea is that if the url has a parameter such as language=French the right text is displayed. I have done the script and tested it and works ok. The problem I have is how to inject this parameter to the links that are on WordPress pages so that when a user selects a particular language, then whichever link they click it should have this parameter. Would you have an idea of how I can do this? Once I do that then I intend to use your plugin to create ‘pretty urls’ with it.

    Thank you in advance.

    Fastele

  46. Aaron June 30, 2009 at 5:04 pm #

    I’m having an issue with WP 2.7.1 where the rewrite rules won’t work until I go to the WP ‘plugin editor’, choose bwb-rewriter.php, and click the “Update File” button (without making any changes). Then my rewrite rules work fine until the next day?? Otherwise WP redirect me to the “Ooops can’t find what you are looking for” page. The permissions on my bwb-rewriter.php file are set to 777 also.

  47. Byron Bennett June 30, 2009 at 5:54 pm #

    Hi Aaron,

    That is bizarre. Did you check to see if there is a plugin conflict? Was it working with 2.7.1 before and has suddenly become screwy? If so, then it’s likely some change has occurred that is giving it grief.

    The things that pop into my mind are caching or maybe it’s not compatible with 2.7.1. Since it happens overnight (maybe) I wonder if there is some job or something that is running and causing it. I really hope it’s just a plugin conflict, though.

    Do you have any ideas.

    Byron

  48. Aaron June 30, 2009 at 11:33 pm #

    After some experimenting I’ve isolated the behavior. If a user goes to a pretty re-written URL before they have logged in to WordPress the rules don’t get applied and they see the “Ooops message”. It would seem that a visitor to the site has to remain logged in for the new rules to be applied. As soon as I log out the pages show “Oooops” again. Is this a “feature”? or should it be working regardless if a user is logged in?

  49. Aaron July 1, 2009 at 12:07 am #

    While not logged in I also just tried adding echo ‘test’;
    Inside each of the fuctions (bwb_flush_rules, bwb_add_rewrite_rules, bwb_query_vars) contained within bwb-rewriter.php to check if the functions where being executed. Each ‘test’ message was successfully sent to the browser before the !DOCTYPE declaration in the HTML so it would seem that the functions are “firing”, but they don’t have an effect if not logged in? Thanks for the help.

  50. Byron Bennett July 1, 2009 at 12:12 am #

    Hi Aaron,

    You don’t happen to be running a plugin that only allows Logged In users to view your content do you? I know there are plugins out there like that.

    I’m trying to think what else it might be…but not coming up with anything.

    BB

  51. Aaron July 1, 2009 at 1:43 am #

    No definitely not. When not logged in the pretty URL’s are redirecting me to my themes 404 page. I notice at the top of the plugin the code:

    // runs the function in the init hook
    add_action(‘init’, ‘bwb_flush_rules’);

    The WP Doc located here:
    (http://codex.wordpress.org/Plugin_API/Action_Reference#Template_Actions)
    States: “These actions are run when a logged-in user opens the home page under the default theme.” So the ‘init’ action is only run if a user is logged in maybe? can I attach the action to an event that occurs for every visitor? Maybe that will work….

  52. Aaron July 1, 2009 at 11:14 am #

    Doh! I had my “template pages” in draft mode and didn’t think about the consequences. Great plugin!

  53. Byron Bennett July 1, 2009 at 11:15 am #

    Whew!!!! You had me stumped!

    Glad it’s working for you,
    Byron

  54. Steve July 6, 2009 at 2:02 pm #

    I’ve implemented/installed the plugin largely unmodified from original install, however am struggling to get the rewrites to work……

    myURL/Site (with page ID of 381, that I am hitting) is:
    hxxp:mysite.com/library/?region=world&country=usa&state=ma

    My understanding is this should rewrite the URL to:
    hxxp:mysite.com/library/world/usa/ma

    Currently the URL does not change when you hit it.

    My rules condition is below –

    $new_rules = array(
    ‘library/(.*)/(.*)/(.*)’ => ‘index.php?page_id=381&region=’.
    $wp_rewrite->preg_index(1).’&country=’.
    $wp_rewrite->preg_index(2).’&state=’.
    $wp_rewrite->preg_index(3)
    );

    I’m on WP 2.7.1………………….I’m stumped as to what I’ve overlooked here…….any thoughts would be much appreciated! 🙂

    Thanks,

    – Steve

  55. Steve July 6, 2009 at 2:03 pm #

    forgot to mention plugin is active and turned on of course 🙂

  56. Byron Bennett July 6, 2009 at 2:12 pm #

    Hi Steve,

    If I’m reading your question properly, you might have it turned around backward.

    Rewriting takes a pretty URL like: hxxp:mysite.com/library/world/usa/ma

    and rewrites it to: hxxp:mysite.com/library/?region=world&country=usa&state=ma

    It’s sole purpose is to allow you to turn those elements (/world/usa/ma) into variables once the URL has been submitted and it hits your code.

    It would take: world/usa/ma and give you variables $region = world; $country = usa; and $state = ma

    Hope that helps.
    BB

  57. Steve July 6, 2009 at 3:43 pm #

    Hi Byron,
    Wow. Fast Reply!

    Yes. I actually was wanting to achieve the reverse…..ie) take the querystring parameters a have these written out as a structured URL.
    ie>
    Take:

    hxxp:mysite.com/library/?region=world&country=usa&state=ma
    and make it:
    hxxp:mysite.com/library/world/usa/ma/

    I’m believe (or at least thought I was) trying to achieve the same result as Karen describes above on her December 8 post.
    I have a wordpress template with php in the code of this page, that takes the existing URL parameters out and pulls appropriate content from the database.

    What I am trying to do it still be able to pull these parameters out of the URL whilst having the URL rewritten to something a little more search engine friendly that doesnt use querystring parameters…..

    Is this possible with your plugin? or any additional workaround perhaps you know of..?
    I had thought I was following Karens ‘cars’ example to achieve the same results, although perhaps not it would seem……??

    Thanks again.

    – Steve

  58. Steve July 8, 2009 at 11:42 pm #

    Ahhh OK. Finally got it lol 😛
    Sorry for catching on slower than most…..is my first dabble with any sort of URL/.htaccess rewrites….

    I ended up adding rewrite code in my .htaccess file, to rewrite querystring parameters appropriately to more SEO/user friendly URLs.

    Then I’ve used the bwb re-writer plugin to point URL to correct content and pull needed parameters out for use on page.

    Thanks for script. Seems to be working well! Great tool.

  59. Karl Jones August 4, 2009 at 9:16 am #

    Hi Byron,

    Thanks for your prompt reply to my questions about BRB-ReWriter.

    Sorry to take so long getting back to you. I wasn’t successful in getting the plugin to work. I was working on a client project, didn’t have much time to explore the problem.

    Seems pretty straightforward, so I was kind of puzzled at the time (overridden by .htaccess at a higher directory level? something obvious and stupid that I obviously stupidly missed?) but had to shelve the mystery for another day.

    Playing with the plugin did have an immediate useful outcome: it helped me solve another design problem, not directly but through some Zen distracted-thinking creativity process.

    I’ve got my own test web site now where I can install and experiment to my heart’s content. On my list of things to do: install and demonstrate BRB ReWriter. I’ll keep you posted as things develop. There’s nothing to see yet, but for future reference here’s the url —

    67.20.67.178/wp28

    Notwithstanding that I haven’t got it running, you’ve done an important piece of work here with your ReWriter; and it’s obvious from the comments that you are dedicated to supporting the community of developers. Thanks again.

    Regards,
    Karl

  60. Byron Bennett August 4, 2009 at 11:42 am #

    @Steve,
    You’re welcome! Sorry for the delayed response!

    @Karl,
    Thanks for the kind words! Glad you’re digging into the plugin. Let me know if you get stuck…Next, I want to create an Admin page for it so people can make their settings without having to change the code in the file. I’m just a little unsure of how whether the database object will be available at the time the Rewriting gets locked in or not, but it could be pretty sweet if a user could easily create rules using text boxes and drop-downs. We shall see!

    Cheers,
    Byron

  61. Catalin HODIS September 30, 2009 at 3:55 pm #

    Problem in using a rule:

    (cannot copy/paste the php code here, it doesn’t save thereply)

    for showing images with Lightbox 2 plugin for Word press.

    Any thoughts?

  62. Catalin HODIS September 30, 2009 at 4:00 pm #

    I cannot write any php code to let you know the rule I am trying to rewrite.
    How do I send you the rule?

    Thanx

  63. Byron Bennett September 30, 2009 at 4:08 pm #

    Hi Catalin,

    You should be able to post the rule if you leave out the < and > . BTW, the way to show < and > is to use the html special codes: &lt; and &gt;

    BB

  64. Catalin HODIS September 30, 2009 at 7:08 pm #

    "web-template/(.*)/(.*)/"

  65. Catalin HODIS September 30, 2009 at 7:08 pm #

    This is the “pretty” url

  66. Catalin HODIS September 30, 2009 at 7:17 pm #

    I tried using " I replaced > with &gt; and still I can’t submit the comment, it contains also http://www.

  67. Catalin HODIS September 30, 2009 at 7:18 pm #

    "http://www.some-other-site.com/images/&quot;.$wp_rewrite->preg_index(1)."/".$wp_rewrite->preg_index(2).".jpg"

  68. Catalin HODIS September 30, 2009 at 7:20 pm #

    ok, I rewrite the comment in one piece.

    $new_rules = array(
    "web-template/(.*)/(.*)/" => "http://www.some-other-site.com/images/&quot;.$wp_rewrite->preg_index(1)."/".$wp_rewrite->preg_index(2).".jpg"
    );

  69. Byron Bennett September 30, 2009 at 7:34 pm #

    Hi Catalin,

    I’m not quite getting it…please email me your question at byron at whypad . com.

    Thanks,
    BB

  70. Daddy38 October 10, 2009 at 12:27 pm #

    I sort of had a feeling of being a little overwhelmed. ,

  71. Drake October 11, 2009 at 8:30 pm #

    Hi Byron,

    There’s something I’d like to ask with regards to search queries within WordPress. As you know how the search queries look like after you’ve search a certain keyword within the wordpress site, I would like to rewrite my search URLs to SEO friendly ones.

    Will it be feasible with this plugin?

    Hope I’m clear with my questions.

    Thanks,
    Drake

  72. Byron Bennett October 11, 2009 at 10:06 pm #

    Hi Drake,

    Just to be clear, as you know, there are 2 sides to re-writing URLs. There’s the presentation side…what the users sees or types into his web browser (ex. http://www.mysite.com/search/searchterms+go+here/ )

    And there’s what WordPress rewriting does…it takes the pretty URL and turns it into something ugly that the server understands: (ex. http://www.mysite.com/search.php?searchterm=searchterms+go+here )

    This plugin helps WordPress handle the second part. It doesn’t create the pretty URLs. It just helps WordPress interpret them and give you something that you can call in get_query_vars (or something that WordPress can use in the same manner). You could use .htaccess rewriting to render the same thing, but WordPress might not know about the variables. This plugin will help you get your query_var into the WordPress framework.

    So, if you’ve got a pretty URL for your search, then this plugin can help get that to be understood by WordPress.

    Hope that helps.

    Byron

  73. Drake October 11, 2009 at 10:13 pm #

    Hi Byron,

    I see, thanks a lot for the clarification. This article does help with understanding how the URL rewrite works… Maybe I can come up with something that reverses the URL rewrite procedure that this plugin offers.

    Thanks a lot,
    Drake

  74. Karl Jones October 14, 2009 at 10:52 am #

    I am eagerly awaiting the latest version of BWB-ReWriter. If you need beta testers, call on me, I’d be happy to help.

  75. Bob Sherron October 23, 2009 at 9:27 am #

    Hey, nice writeup, and great support in the comments. I have a very similar situation to what you put forth here, with the exception that as you go further down the url, the parameters become optional. I handled this by writing three rules, each one deals with the shorter url. Like so:

    $new_rules = array(
    ‘our-network/(.*)/(.*)/(.*)’ => ‘index.php?page_id=7&region=’.
    $wp_rewrite->preg_index(1).’&subregion=’.
    $wp_rewrite->preg_index(2).’&city=’.
    $wp_rewrite->preg_index(3),
    ‘our-network/(.*)/(.*)’ => ‘index.php?page_id=7&region=’.
    $wp_rewrite->preg_index(1).’&subregion=’.
    $wp_rewrite->preg_index(2),
    ‘our-network/(.*)’ => ‘index.php?page_id=7&region=’.
    $wp_rewrite->preg_index(1)

    );

    There’s probably a more elegant way to do this with the regex, but it worked for me. The kicker is that if you go the other way, it doesn’t work at all, so order of rule addition is definitely in play.

    Thanks for the tip!

  76. san November 4, 2009 at 6:40 am #

    hi,

    i’m not able to use the plugin. i need the following url
    http://mysite.com/?page_id=29&c_id=1

    to be changed to
    http://mysite.com/pagename/1

    I used the above set up, but my function bwb_add_rewrite_rules() is not calling. When i echo variable inside it it doesn’t get displayed.

    Is my installation has some problem?

    I’m not using Permalinks also.

    When i use Permalinks, i’m able to get the url as

    http://mysite.com/pagename/?c_id=1 – which doesn’t satisfy me.

  77. Karl Jones November 4, 2009 at 8:35 am #

    Hi Byron,

    I got it working.

    You’ve created a powerful and much-needed plugin, thanks again for making this happen.

    Karl

  78. san November 19, 2009 at 1:57 am #

    Hi, i’ve posted my problem earlier.

    Now, the function gets called, but i’m getting the below error.
    Fatal error: Call to a member function preg_index() on a non-object in

  79. TheToolWiz December 25, 2009 at 4:13 am #

    Hi, I’ve been searching around for a while for something that lets me pass in some parameters to page, and this is the only thing I’ve found! It looks great!

    However, I’m running WP V2.9 and when I try to activate the plugin, I get an error saying headers are missing.

    Any solution?

    Thanks
    -David

  80. TheToolWiz December 25, 2009 at 4:19 am #

    whoops …

    It seems there are two folders in the zip file:

    /bwb-rewriter/bwb-rewriter/bwb-rewriter.php

    I moved the file up:

    /bwb-rewriter/bwb-rewriter.php

    and it installs just fine.

    (I used the Add New function in the Plugins admin page, and selected Upload, used Browse to find the .zip file, then installed it. You might want to remove one of the folders.)

  81. agustinh February 10, 2010 at 7:09 am #

    Awesome. Thank you very much for this plugin.

  82. Salman April 26, 2010 at 6:36 am #

    **** I need a quick help *****

    It didn’t work out that way. Even though the rewrite is mentioned when I used Rewrites Viewer Plugin by Dagon Design where wordpress listed the rewrite query as:

    [videos/(.*)/(.*)/(.*)] => wp-content/themes/Videographer/yshortdown.php?yid=$matches[1]&yfn=$matches[2]&qua=$matches[3]

    But it does not get rewritten. Seems another solution is needed. Thanks for help!

  83. Salman April 27, 2010 at 1:23 am #

    STILL WAITING FOR ANY RESPONSE FOR THE ISSUE BELOW 🙁

    **** I need a quick help *****

    It didn’t work out that way. Even though the rewrite is mentioned when I used Rewrites Viewer Plugin by Dagon Design where wordpress listed the rewrite query as:

    [videos/(.*)/(.*)/(.*)] => wp-content/themes/Videographer/yshortdown.php?yid=$matches[1]&yfn=$matches[2]&qua=$matches[3]

    But it does not get rewritten. Seems another solution is needed. Thanks for help!

Trackbacks/Pingbacks

  1. WordPress: Prevent WP from Overwriting Custom htaccess Rules | WhyPad - September 11, 2008

    […] I have created a plugin that facilitates that and makes it pretty easy.  You can get the plugin here.  If, however, your app needs to bypass the WordPress app, you will need to put your rewrite rules […]

Powered by WordPress. Designed by Woo Themes