Creating Category-based Navigation with Description (a la Grid Focus)

UPDATE 24 December 2009:
Changed the main code on line 11 from $get_cat_id = '/cat-item-[0-9]+"/'; to $get_cat_id = '/cat-item-[0-9]+/'; (without double quotes). This is to deal with the additional “current-cat” class added automatically when a category is currently displayed.

One of Grid Focus theme‘s most prominent feature is its navigation bar with link name and description, depicted below in its modified version at Logo Design Love:

logodesignlove-nav

These navigation links (and their descriptions) are hard-coded into the theme, though, so they’re a little less flexible. For a theme I’m currently working on, I had an idea of creating a navigation like this but using a list of categories instead. The description text will then be pulled from each category’s description, which can be set directly via the Dashboard menu at Posts > Categories, therefore preventing users from having to mess with PHP file:

WordPress add category description panel

The PHP Code

When displaying a list of categories, the function to use is obviously wp_list_categories. However, that function only allows us to use the category’s description as a title property of the anchor link (and nowhere else), for example:

<li class="cat-item cat-item-3">
  <a href="http://wplover.com/category/development/" title="Hack Away">Development</a>
</li>

No luck there, because for our category-based navigation to work, we need to wrap the description inside a span tag:

<li class="cat-item cat-item-3">
  <a href="http://wplover.com/category/development/" title="Hack Away">Development<span class="cat-desc">Hack Away</span></a>
</li>

Our solution then, is to create a little hack where we manipulate the output of wp_list_categories() and inject the descriptions there.

Here’s my code, which should go into functions.php in your theme:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Create a modified output of wp_list_categories where the categories description
// is added inside a span tag within the link like so:
//<li><a title="Category Description" href="#">Category Name<span>Category Description</span></a></li>
function list_cats_with_desc() {
  $base = wp_list_categories('echo=0');
 
  // wp_list_categories adds a "cat-item-[category_id]" class to the <li> so let's make use of that!
  // Shouldn't really use regexp to parse HTML, but oh well.
  // (for the curious, here's why: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 )
 
  $get_cat_id = '/cat-item-[0-9]+/';
  preg_match_all($get_cat_id, $base, $cat_id);
 
  // Let's prepare our category descriptions to be injected.
  // Format will be <a>category-name<span>category-desc</span></a>
  $inject_desc = array();
 
  $i = 0;
  foreach($cat_id[0] as $id) {
    $id = trim($id,'cat-item-');
    $id = trim($id,'"');
 
    $desc = trim(strip_tags(category_description($id)),"\n");   // For some reason, category_description returns the
                                                                // description wrapped in an unwanted paragraph tag which
                                                                // we remove with strip_tags. It also adds a newline
                                                                // which we promptly trim out.
    if($desc=="") $desc = "Add Description";
 
    $inject_desc[$i] = '<span class="cat-desc">' . $desc . '</span></a>';
    $i++;
  }
 
  // Now we inject our descriptions
  $base_arr = explode("\n", $base);
 
  $base_i = 0;
  foreach($inject_desc as $desc) {
 
    // We check whether there's an occurence of "</a>"
    while(strpos($base_arr[$base_i], "</a>") === false) {
      $base_i++;
    }
 
    // If we find one, inject our description <span>
    $base_arr[$base_i] = str_replace("</a>", $desc, $base_arr[$base_i]);
 
    $base_i++;
  }
 
  $base = implode("\n", $base_arr);
  echo $base;
}

After that, calling this list_cats_with_desc() function anywhere in your theme will result in something like this:

<li class="categories">Categories
  <ul>
	<li class="cat-item cat-item-3"><a href="http://wplover.com/category/development/">Development<span class="cat-desc" title="Hack Away" Hack Away</span></a></li>
	<li class="cat-item cat-item-4"><a href="http://wplover.com/category/themes/" title="Pretty Ones">Themes<span class="cat-desc">Pretty Ones</span></a></li>
	<li class="cat-item cat-item-5"><a href="http://wplover.com/category/news/" title="Get Updated">News<span class="cat-desc">Get Updated</span></a></li>
  </ul>
</li>

Notes Regarding the Function

  • For this to work, wp_list_categories() must output the links in a list style format. On line 5 of my function above, you can tweak the parameters more (say, to exclude some categories), but the ‘style’ parameter must remain ‘list’. Refer to the Codex for more info about wp_list_categories’ parameters.
  • If a category does not have any description, it will use the default text “Add Description” (line 27 above). Change this to anything you wish. Ideally for our navigation, every category must have a description.

The CSS

After we get the HTML list formatted nicely, the last thing to do is to CSS it. Borrowing and tweaking from Grid Focus’ code, you can use something like this as an example:

.categories li a {
	font-weight: bold;
	letter-spacing: 1px;
	text-transform: uppercase;
	float: left;
	display: block;
}
.categories li a span.cat-desc {
	color: #888;
	font-size: 0.9em;
	font-weight: normal;
	text-transform: lowercase;
	display: block;
}

The most important thing is to throw a display:block for the .cat-desc so the description stand on its own underneath the category name but still clickable at the same time.

The End

Anyway that’s it! Let me know if you have any thoughts to share!

Latest Links More →

Classy Plugins

Eric Mann uses classes in his non object-oriented WordPress code. Here’s why.

Playing Nice with the “the_content” Filter

This great article could be useful if for some reason you have a need to filter the_content in your theme.

Google Goes After Links In WordPress Themes

New post from the Search Engine Roundtable: Someone “…received a response from Google to a reconsideration request that the only way his site will be reincluded in Google is if he removes all or most of the links in those WordPress themes.” The problem is that those links are in the form of sponsored links on footer (a practice I saw a lot in the past, not so much in the present).

I don’t think it will be easy, or even possible, to do what Google requested. If a theme contains an upgrade notification feature it might be possible to do, but even then the users might choose not to upgrade.

Secondly, if this is true, I wonder whether Google differentiates between credit links (“Designed by…”) and sponsored links. I would say they should, but then again I’m not a SEO guy.

Theme Options Gallery

New favorite blog: Theme Options Gallery by Konstantin Kovshenin, discussing “the best (and the worst) theme options screens around”. Loving the in-depth article and discussions already available there.

Dive into Responsive Prototyping with Foundation

Pretty safe to say that if it shows up on A List Apart, it’s going to be the de facto standard. Time to learn some Foundation.

Google HTML/CSS Style Guide

Couple of days ago we got Starbucks’ style guide, and now here’s another by Google. I think the interesting thing is the rule to “\[o\]mit the protocol from embedded resources“. So instead of typing <script src="http://www.google.com/js/gweb/analytics/autotrack.js"></script>, they recommend to type <script src="//www.google.com/js/gweb/analytics/autotrack.js"></script> instead (without the http part). Never heard of that before.

“I Woke Up but My Server Wasn’t There”

Robb Shecter’s WordPress site got popular overnight thanks to Reddit and went down immediately. The interesting aspect is that the site was new and it’s on a relatively high-powered server. The author then found that the theme he used in particular was doing too many (47!) server requests at a time, and the site ran along very well after switching back to Twenty Eleven.

I think it’s an important read for any theme developers out there.

Read the story here

Modern Web Development – Part I: The Webkit Inspector

A superbly detailed article, part one of a series about web development toolchain.

Crayon Syntax Highlighter plugin

I’ve always been on the hunt for that perfect syntax highlighter plugin. Currently I’m using WP-Syntax, which does its job very well. However I’ve just found this plugin called Crayon Syntax Highlighter, which could be a good contender for the best WordPress syntax highlighter plugin out there.

It looks good, and I like the little toolbar on top of the code box, with the small icons. Additionally, it also offers a lot of customization options. Lastly, it seems to support the same pre tags to wrap the code, similar WP-Syntax, so if I do make the switch, my old codes will still be highlighted correctly.

Starbucks Style Guide

The Starbuck website has its own style guide, accessible for public. I think its a neat idea, wouldn’t it be cool if themes have their own style guide? Pretty sure it will be helpful both to users or developers alike, if time consuming to write.

Also, I wonder what they use for the various toggles panel on the top right corner like on this page. It shows background, baseline, boxes, can be used to change windows size as well. Looks like it’s custom coded, imagine how super useful it can be if it’s a jQuery plugin.

NHP Theme Options Framework

I love theme options frameworks. And I want you guys to check this new framework called NHP. It passes my “does its UI look like the rest of WordPress enough?” test (screenshots here), it has tons of field types, and even offer validations, too.

Can’t wait to test and probably use it too in my to-be-released theme hint hint

What Dev4Press thinks WordPress needs…

This post at Dev4Press outlines what MillaN, its author, thinks would be a necessary addition to WordPress.

Based on the comments, it appears that a lot of people agree with this list. Some of the items mentioned can be achieved with plugins (e.g Tax Meta Class to add meta data to taxonomy items, Custom Post Types Relationships for, well, creating custom post type relationships), so expect there to be a bunch of debates about what should and shouldn’t go to the core.

I like his list, but I disagree with his assessment that we don’t need new core themes. We do, especially to bring about the standard for how a theme options should be designed. This is the aspect that desperately needs to be standardized. Different theme companies and individual theme designers have their own idea of how the theme option UI should look, and it’s hurting the users.

Upgrading from WordPress 1.5

I recently spotted this interesting Ask Metafilter thread where user gd779 tries to find a way to upgrade his old, WordPress 1.5 install. One of the answer is pretty detailed:

I think the right approach is going to be:

  1. Do a full backup of your WordPress files
  2. Do a full database backup (mysql dump using phpMyAdmin or similar)

Then, from your 1.5.2 install:

  1. Upgrade to 2.0
  2. Upgrade to 2.5.1
  3. Upgrade to 3.0
  4. Upgrade to 3.3.1

It is quite fascinating thinking about the solution to this. There’s an official Codex page called Updating WordPress, but it doesn’t seem to go that far back in time.

Smashing Special: What’s Going On In The WordPress Economy?

Siobhan McKeown wrote this awesome, birds-eye view of the whole WordPress economy. Make sure to read this two-part article so you know what’s up with WordPress and identify what opportunity lies ahead.

I agree with Matt’s prediction on that article:

I think the next big opportunity is around agencies and consulting—there will be five to six companies as large as Automattic, just providing high-end consulting and services to the large customers who are adopting WordPress en masse.

Start with Part I of the article.

Automatic responsive images for WordPress

The one issue with creating responsive web design is in displaying images, especially getting the most appropriate size in a particular screen size. One solution for it is the Responsive-Enhance jQuery plugin. It works by loading small-sized images by default, then checks the screen size and loads the bigger version if necessary.

According to its creator, Josh Emerson:

This results in a faster perceived page load speed, but a slower actual speed. I’m happy with this solution as I care more about perceived speed than actual speed.

This tutorial by Keir Whitaker takes the whole thing further by teaching us how to apply Responsive-Enhance in WordPress.

The WordCamp Central Site Redesign

The WordCamp Central has been redesigned, now sporting pleasant shades of blue. I particularly like the individual WordCamp page like this one for San Francisco, which features date, location, and archive links to past WordCamps there.

A little peek under the hood shows that the site now uses a Twenty Ten child theme called “WordCamp Central 2012″. The site uses a plugin called WP Event Ticketing for ticketing purposes, and WP Super Cache for speed.