Why I’m just a little code monkey

Sometimes you’ve just gotta leave it to the pros

I had this little problem with the WordPress Codex a while back – I wanted to display a link to feeds for my tags on the tag pages. WordPress is pretty good about presenting the data – I used ucwords(single_tag_title("", false)) to properly display the tag names at the top of the page (see here), but the codex didn’t have a function for returning the link part (i.e. /fly-fishing/) without a ‘tag id’ and the additional page numbering was getting in the way too. So I hacked together this work-around:

if (preg_match("/\/page\//",$_SERVER['REQUEST_URI'])) {
$feedtarget = $_SERVER['REQUEST_URI'];
$feedreplace = array ('|/page/2|','|/page/3|','|/page/4|','|/page/5|','|/page/6|','|
/page/7|','|/page/8|','|/page/9|','|/page/10|','|/page/11|','|/page/12|','|/page/13|','|
/page/14|','|/page/15|');
$feedchange = array ('','','','','','','','','','','','','','');
$feedfixed = preg_replace($feedreplace,$feedchange,$feedtarget);
$feedmatch = $feedfixed.'feed/';
} else {
$feedmatch = $_SERVER['REQUEST_URI'].'feed/';
}

And was stuffing that $feedmatch bit into the link by echoing it after bloginfo(‘url’).

What I can manage to get out the door usually works, even if it is less than elegant. Ok, way less than elegant (and limited on the page number end too). I could use the excuse that I was in a rush, but the fact is I spent at least an hour getting it to work right, and once it did I felt the hero in my own mind.

After re-arranging my categories a bit, I thought about extending the ‘patch’ to those and posting the work for others. It was then I realized that was some craptastic code like you read about. So I ask a friend if he could help me clean up the array portion. He does one better, by reducing my entire bunk to one line:

$feedmatch = preg_replace('/\/page\/[0-9]+/', '', $_SERVER['REQUEST_URI'], 1).'feed/';

Proving once and for all that Regular Expressions should be basic coursework for accounting grads (or at least qualified CPE). And I should stick to tumbling numbers and fly fishing.

Leave a Reply

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