I want to order categories based upon the latest post time

This code list all parent categories on the basis of recent publish post in that category.

function ravs_cat_list(){

    /* all parent categories*/
    $args = array(
            'parent' => 0
        );
    $cats = get_categories( $args );

    /* get recent post from each category */
    foreach( $cats as $cat ):
        $args = array(
                'numberposts' => 1,
                'category' => $cat->term_id
            );
        $recent_posts = wp_get_recent_posts( $args );
        /* category list */
        $cat_list[]=array(
                'id' => $cat->term_id,
                'name' => $cat->name,
                'post_date' => $recent_posts[0]['post_date']
            );
    endforeach;

    /* sort $cat_list on basis of resent publish post */
    function sortFunction( $a, $b ){
        return strtotime($a["post_date"]) - strtotime($b["post_date"]) > 1 ? -1 : 1;
    }
    usort($cat_list, "sortFunction");

    /* print list of sorted categories */
    echo'<ul class="cat-list">';
    foreach ($cat_list as $cat):
    ?>
    <li><?php print_r($cat['name']); ?></li>
    <?php
    endforeach;
    echo '</ul>';
}

Leave a Comment