Sort Categories by Most Recent Entries

August 12th, 2009

catsort

I just completed a little bit of magic to sort Wordpress categories based on the most recent entry in each category, and I thought I’d share:

function get_cat_order($categories) {
    foreach($categories as $category) {
        $cat_id=get_cat_ID($category);
        $myposts = get_posts('numberposts=1&category='.$cat_id);
        $arrstr.='"'.strtotime($myposts[0]->post_date).'"=>"'.$category.'",';
    }
    eval('$catorder=array('.substr($arrstr, 0, -1).');');
    ksort($catorder);
    $catorder=array_reverse($catorder);
    foreach($catorder as $key=>$val) {
        $sortedCategories[]=$val;
    }
    return $sortedCategories;
}

My function get_cat_order() accepts an array of categories and returns a sorted array:

$categories=array('Life','Technology','Style','Fitness','Food','Business');
$categories=get_cat_order($categories);

I then feed this sorted array to another function which creates the category features as displayed on my homepage. The result is a dynamic listing of categories based on the post_date of the most recent entry in each category. In other words, the category which has the most recent entry is displayed first and the other categories are listed in descending order.

Do you have a more efficient or more elegant solution? Let me know in the comments below. Constructive criticism is always welcome.

What do you have to say?