Wordpress Sliding Doors – take 2 [PHP]

June 24th, 2008 by Daniel | Posted in PHP | 1 Comment

I have had a lot of feedback over one of my first ever posts, Wordpress: Sliding Doors details how you can convert wp_list_categories into a subtle HTML markup so that we can use the sliding doors principle. However the method I described in my original post no longer works. After a lot of thinking and head scratching I have discovered a new, if not better, way to achieve the same results.

By correctly formatting the wp_list_categories output, we can explode the output into an array of the categories. We can then split each string and add our HTML code in before and after the category name.

   1: <ul class="menu">
   2:     <li <?php if(is_home()) echo 'class="selected"'; ?>><a href="/"><span>Home</span></a></li>
   3:     <?php
   4:         // get all the categories
   5:         $cats = explode('<br />', wp_list_categories('echo=0&show_count=0&title_li=&style=none&exclude=1'));
   6:         // remove the last value
   7:         array_pop($cats);
   8:         foreach ($cats as $cat)
   9:         {
  10:             // what it comes through as
  11:             // <a href="http://dtsn.co.uk/category/uncategorized/" title="View all posts filed under Uncategorized">Uncategorized</a><li>
  12:             // get the position of the first >
  13:             $beforeName = strpos($cat, '>')+1;
  14:             $afterName = strpos($cat, '</a>');
  15:             $length = $afterName - $beforeName;
  16:             $name = substr($cat, $beforeName, $length);
  17:
  18:             if ($beforeName > 0) {
  19:                 $class ='';
  20:                 // are we on this page?
  21:                 if (is_category($name)) {
  22:                     $class=' class="selected"';
  23:                 }
  24:
  25:                 // add the opening span tag behind the opening anchor tag
  26:                 echo '<li' . $class . '>' . substr($cat, 0, $beforeName) . '<span>' . $name . '</span></a></li>';
  27:             }
  28:         }
  29:     ?>
  30: </ul>

If you have any problems implementing this please leave a comment below.

Digg This Stumble

Leave A Comment

Blurb

Hi I'm Daniel and I'm a front-end web developer. These are my thoughts, interests and ideas. Hope you enjoy! Dont forget to subscribe to the feed.

Scrapbook

  • *
  • *
  • *
  • *
See More