0

I have four categories:

  • 2013
  • 2012
  • 2011
  • 2010

These categories contain posts that are also categorized

  • Cat A
  • Cat B
  • Cat C

So basically there's a bunch of posts that are categorized (2013, Cat A), (2013, Cat B), (2012, Cat A), (2012, Cat C), etc

Without having to add Cat A, Cat B and Cat C as four sets of child categories under 2013, 2012, 2011 and 2010 is there a way that I can programmatically list those unique subcats with posts under each year so that they list as:

  • 2013
    • Cat A
    • Cat B
    • Cat C
  • 2012
    • Cat A
    • Cat B
    • Cat C
  • 2011
    • Cat A
    • Cat B
    • Cat C
  • 2010
    • Cat A
    • Cat B
    • Cat C

AND have those subcats link to their respective category page?

1 Answer 1

0

Untested, but I think this will do the trick!

<?php

// Get date Categories
$date_cats = get_categories(array(
    'include' => '1,2,3,4'
));

// Loop through date categories
foreach($date_cats as $date_cat) :

    // Get link of current date category
    $date_cat_link = get_category_link( $date_cat->cat_ID ); ?>

    <ul>
        <li><a href="<?php echo $date_cat_link; ?>"><?php echo $date_cat->name; ?></a>
            <ul>
            <?php
            // Get ID of current date category
            $date_cat_id = $date_cat->cat_ID;

            // Get ABC categories
            $abc_cats = get_categories(array(
                'include' => '5,6,7'
            ));

            // Loop through ABC catagories
            foreach($abc_cats as $abc_cat) :

                // Get ID of current ABC category
                $abc_cat_id = $abc_cat->cat_ID;
                // Get link of current ABC category
                $abc_cat_link = get_category_link( $abc_cat->cat_ID );

                // Run a query for posts that are in this date category AND this ABC category
                $query = new WP_Query( array(
                    'posts_per_page' => -1,
                    'category__and' => array( $date_cat_id, $abc_cat_id )
                ));

                // If there are posts, show this ABC category's name and link
                if ( $query->have_posts() ) { ?>

                <li><a href="<?php echo $abc_cat_link; ?>"><?php echo $abc_cat->name; ?></a></li>

                <?php } ?>

            <?php endforeach; ?>
            </ul>
        </li>
    </ul>

<?php endforeach; ?>
1
  • That's the one! Commented Apr 9, 2014 at 20:02

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.