0

How can I get 5 categories ordered by publish date of it's most recent post?

I basically need 5 most recent categories that were used in recent posts.

0

Okay, seems like this is not supported out of the box. At least I didn't find any arguments you can use for WP_Term_Query (which is the function used behind get_categories()).

So I had the following idea

  1. retrieve all categories
  2. get latest post from each category
  3. save category id & post date in an array
  4. order by post date
  5. return the 5 most recent category ids
function get_most_recent_categories($limit = 5) {
    // retrieve all categories
    $categories = get_categories();
    $recent_posts = array();
    foreach ($categories as $key=>$category) {
        // get latest post from $category
        $args = array(
            'numberposts' => 1,
            'category' => $category->term_id,
        );
        $post = get_posts($args)[0];
        // save category id & post date in an array
        $recent_posts[ $category->term_id ] = strtotime($post->post_date);
    }

    // order by post date, preserve category_id
    arsort($recent_posts);

    // get $limit most recent category ids
    $recent_categories = array_slice(array_keys($recent_posts), 0, $limit);

    return $recent_categories;
}
  • Thank you this is working fine! But how fast this function will be assuming we have 10, 50, 100 categories? – CMTV Jul 24 '17 at 8:56
  • @CMTV I don't know, you'll have to test this. Another possible solution would be to write a custom query. But considering page/query cache, even this one shouldn't hurt performance – kero Jul 24 '17 at 9:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.