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
- retrieve all categories
- get latest post from each category
- save category id & post date in an array
- order by post date
- 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;
}