Is it possible to print all categories used for a specific year in a hierarchical tree with all the post titles underneath each category title?



1 Answer 1


The start is easy. Let's fetch all the posts from 2015:

$posts = new WP_Query( 'year=2015' );

Now, we have an array of post objects, which we must sort into categories, duplicating them if they have multipe categories. The result goes into a multidimensional array.

$categorized_posts = array ();
foreach ($posts as $post) {
  $post_cats = wp_get_post_categories ($post->ID, array('fields' => names));
  foreach ($post_cats as $post_cat) {
    $categorized_posts[$postcat][] = $post->ID;

So $categorized_posts is an array with category names and for every category name there is an array of ID's of the corresponding post. What's missing is a hierarchical tree. We're going to loop through all categories, printing them along the way with the corresponding post titles. To do this hierarchically we use the recursive function found here, which we modify to output post titles.

// this goes in the template where you want the tree to be printed
wpse237979_hierarchical_category_tree (0, $categorized_posts );

// this goes in functions.php
function wpse237979_hierarchical_category_tree ( $cat, $categorized_posts ) {
  $next = get_categories('hide_empty=false&orderby=name&order=ASC&parent=' . $cat);
  if ($next) {    
    foreach ($next as $cat) {
      if (array_key_exists($cat,$categorized_posts)) {
        echo '<ul><li><strong>' . $cat->name . '</strong>';
        // now loop through the gathered ID's of posts belonging to this category
        $current_cat_posts = $categorized_posts[$cat];
        foreach ($current_cat_posts as $current_cat_post) {
          $this_post = get_post ($current_cat_post);
          echo '<h2>' . $this_post->post_title . '<h2>';
    wpse237979_hierarchical_category_tree( $cat->term_id, $categorized_posts );
  echo '</li></ul>'; echo "\n";

Note: I didn't actually test this code, so some debugging may be necessary, but I trust you get the general idea.

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.