0

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?

1 Answer 1

0

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).

Example:

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.

2
  • 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
    Commented Sep 2, 2012 at 19:25
  • 1
    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. Commented Sep 2, 2012 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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