WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm building an ajax archive tool. Among the functionalities it can list categories.

For each entry i'm displaying the category name (with an anchor that links to the category page) and the number of entries for the category.

I would also like to show the date when a post was last added to the category.

Is there a way to do this without having to make a new wp_query for each category getting the last post and then it's date?

share|improve this question
up vote 0 down vote accepted

Unfortunately no; the categories are stored separately in the database and would each require their own query.

I like to stick to built in wordpress functions as much as possible, but you could make a custom query to find the latest post from each category using the wp_term_relationships table.

It stores the post id (object_id) , and the category id (term_taxonomy_id) in the order they were created (larger post ids were created more recently).


global $wpdb;
    $table_name = $wpdb->prefix . "term_relationships";
    $sql = "SELECT object_id FROM ".$table_name." WHERE term_taxonomy_id =" . $category_id . "ORDER BY object_id DESC LIMIT 1";
    $result = $wpdb->query($sql);
    $post = get_post($result->object_id);

This could be done easily if you have a static list of category ids (find them in thewp_terms table); If your categories are dynamic, I would consider using get_terms to populate the $category_id variable above in a foreach loop.

share|improve this answer
Eventually I used get_posts() with the category ID and then get_the_time(), I don't think the overhead would be much more than using $wpdb, isn't it? – Bakaburg Sep 2 '12 at 19:25
The overhead is minimal...but only grabbing one field column value from a table should be faster than pulling all columns (get_posts()). Unless you have an extremely large database of posts, what you did should be great. – Douglas.Sesar Sep 2 '12 at 19:29

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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