Lookhappy Design

18 March 2015

Displaying Custom Posts by Taxonomy Order With Taxonomy Titles

This was another very tricky thing to wrap my head around. So what we want to do is list a custom Taxonomy item, and then below that all the posts that have that taxonomy applied to them.
So for example it should look like this:

TAXONOMY ITEM 1
– post 1
– post 2

TAXONOMY ITEM 2
– post 3
– post 4

and so on.
Sounds like a fairly logical thing to want to do, but actually doing it is another thing – very tricky if you ask me!
Well here’s what we do…
We start off by getting all the terms of the custom taxonomy, and then we loop through them to grab the ID of each one.
We can then echo out a header for the category, and then we chuck in a query_posts, of which we filter by tax_query to check to only display posts from the current taxonomy item, and we filter by meta_query as well to show featured items at the top of the list within the current category.
What a mouthful, but the final code looks like this:

<?php
    // get all the categories from the database
    $cats = get_terms( 'offer_tax' );

    // loop through the categories
    foreach ($cats as $cat) {
        // setup the category ID
        $cat_id = $cat->term_id;
        // Make a header for the category
        echo "<h2>".$cat->name."</h2>";
        // create a custom wordpress query

        query_posts(array( 
            'post_type' => 'special_offers',
            'showposts' => -1,
            'tax_query' => array(
                array(
                    'taxonomy' => 'offer_tax',
                    'terms' => $cat_id,
                    'field' => 'term_id',
                )
            ),
            'orderby' => 'meta_value',
            'order' => 'ASC',
            'meta_query' => array(
                array  (
                    'key' => 'featured',
                )
            ),
            )
        );

        // start the wordpress loop!
        if (have_posts()) : while (have_posts()) : the_post(); ?>

            <div class='special_offer'>
                <h3><?php the_title(); ?></h3>
                <span class='offer_text'><?php the_content(); ?></span>
            </div> 

    <?php endwhile; endif; // done our wordpress loop. Will start again for each category ?>
<?php } // done the foreach statement ?>

I hope this helps someone else in the future as it took a lot of head scratching to wrap my brain around it