• I am developing a WordPress site for a client in which every month there are two posts published into a new category (named for the topic of that month).

    I’m looking for a way to display the list of categories (topics) in chronological order. I’m thinking of two possible ways this can be achieved:

    1. List the categories and order by date. I have not found a good way to do this, probably because categories aren’t time-stamped. Maybe there’s a way to look to see how recent the posts in the category are and use that information to determine the order the categories?

    2. List the posts in a loop where I only display the category name for that post. The problem here is that since there are always two posts per category, the category name will show up twice. Is there a way to show only one post per category in a loop?

    Thanks for your help in advance!

Viewing 1 replies (of 1 total)
  • This should be close to what you want, if I understand correctly. You will need to adjust the display in the foreach loop.

    $sql = "
    SELECT t.name, p.post_date, p.post_title
    FROM $wpdb->terms t
    JOIN $wpdb->term_taxonomy tt ON (t.term_id = tt.term_id
          AND tt.taxonomy = 'category')
    JOIN $wpdb->term_relationships tr ON (tt.term_taxonomy_id = tr.term_taxonomy_id)
    JOIN $wpdb->posts p ON (tr.object_id = p.ID)
    WHERE t.name NOT IN ('Uncategorized')
       AND p.post_date = (
          SELECT max(p2.post_date)
          FROM $wpdb->posts p2
          JOIN $wpdb->term_relationships tr2 ON (p2.ID = tr2.object_id)
          JOIN $wpdb->term_taxonomy tt2 ON (tr2.term_taxonomy_id = tt2.term_taxonomy_id)
       WHERE tt2.term_taxonomy_id = tt.term_taxonomy_id
       )
       AND p.post_type = 'post'
       AND p.post_status = 'publish'
    ORDER BY p.post_date DESC
    ";
    //echo '<pre>' . $sql . '</pre>';
    
    $recs = $wpdb->get_results($sql);
    //print_r('<pre>RECS:');print_r($recs);print_r('</pre>');
    foreach ($recs as $rec) {
       echo "$rec->name, $rec->post_date, $rec->post_title<br />";
    }
Viewing 1 replies (of 1 total)
  • The topic ‘List of categories sorted by Date’ is closed to new replies.