Better Category Sorting
posted on march 2, 2003, tag: movable type
Right, so I was supposed to write that tutorial about category sorting using PHP. I must have forgotten. Better late than never, I suppose. Here goes: Ellie was creating a new section for her website—a photo blog—and came across a bit of a problem.
She wanted the front page of this section to show the most recent photo from each category. The important thing was that these photos were listed by last update, descending. That means newest photo on top, oldest photo on bottom. The problem is, MT doesn't seem to allow you to organize categories in this fashion. No matter how hard I tried, I couldn't get them to display in any order other than alphabetically by label. That wasn't going to work, so I set out to find a solution.
This is an example of the default sorting method for categories in MT (top), and the way you'll be able to sort them when we're done here (bottom). That's right: by date [last updated]. Yay.
Okay, here's how you do it. You're gonna need PHP. At least for this version of the tutorial. You could probably do this using ASP or ColdFusion, but I'm not gonna bother with showing you how. The array system in ASP sucks (it's bad enough I have to use ASP all day at work), and I don't have anywhere to test or show you the ColdFusion output. So, anyway, PHP. Alright.
This is how you would display a list of the last entry in each category, sorted by Category Label (title):
<MTCategories><MTEntries lastn="1">
<MTDateHeader>
<p><b><$MTCategoryLabel$></b> | <$MTEntryTitle$> <font class="date"><MTDateHeader>{<$MTEntryDate format="%Y-%m-%d %H:%M:%S"$>}</MTDateHeader></font></p>
</MTDateHeader>
</MTEntries></MTCategories>
And now, we shall use some fancy PHP code to sort these categories by date last modified. First, you're gonna need to build an array of all the categories. Like this:
<MTCategories><MTEntries lastn="1">
<MTDateHeader>
<?php
$temp_date = '<$MTEntryDate format="%Y-%m-%d %H:%M:%S"$>';
$temp_content = '
<p><b><$MTCategoryLabel encode_php="q"$></b> | <$MTEntryTitle encode_php="q"$> <font class="date"><MTDateHeader>{<$MTEntryDate format="%Y-%m-%d %H:%M:%S"$>}</MTDateHeader></font></p>';
$content_array[$temp_date] = $temp_content;
?>
</MTDateHeader>
</MTEntries></MTCategories>
You should replace everything in the $temp_content variable (that's where you see <p><b> and so on) with your content.
You might notice this doesn't actually output anything. That's right, it doesn't. We need to do that separately. But now we have an array of all the categories built and ready to use. So let's use 'em:
<?php
krsort($content_array);
reset($content_array);
foreach ($content_array as $item) {
echo $item . "\n";
}
?>
That block of code sorts the array by date and then, using the foreach loop, outputs the categories in this new date-based order. Pretty simple, yes?