How to order posts by title after they have already been sorted by category


I’m not an expert at much, so please excuse me if this is an easy question… but it’s got my head spinning.

I have an archive template (adapted from a standard ‘enfold’ theme template) which I am using to display a simple list of books. Following a tutorial I found elsewhere, I created the loop below.

If I understand the code correctly, the first part of the block below is used to fetch and sort the taxonomy values for the custom post type. So, it finds ‘Romance’, ‘Horror’, ‘Humour’ etc. It then displays posts with those taxonomy values together. So, I have a little table with a taxonomy value as a heading, and the posts with that taxonomy value in the table. Then I have a table for the next taxonomy type, and the relevant posts, one for each taxonomy value.

The ‘orderby’ in the original code sorts the taxonomy values by name.

It works perfectly, except the posts inside each ‘taxonomy-table/group’ are in random order, and I need to sort them by post title.

I want to sort the posts (inside their taxonomy-sorted tables) by title. How do I do this? I’ve tried copying every bit of code I can find on the subject but nothing has come close to working.

The loop used is;

<?php //start by fetching the terms for the booktype taxonomy
$terms = get_terms( 'booktype', array(
    'orderby'    => 'name',
    'order'   => 'DESC',
    'hide_empty' => 0
) );

foreach( $terms as $term ) {
    // Define the query
    $args = array(
        'post_type' => 'fiction',
        'booktype' => $term->slug
    $query = new WP_Query( $args );

    // output the book type in a heading tag                
    echo'<h4>Book Type ' . $term->name . '</h4>';
    echo '<table>';
    echo '<tr>';
    echo '<th>Title</th>';
    echo '<th>Author</th> ';
    echo '<th>Published</th>';
    echo '<th>ISBN</th>';
    echo '<th>Sales</th>';
    echo '</tr>';
    while ( $query->have_posts() ) : $query->the_post();
            <td><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></td>
            <td><?php the_field( 'book-author' ); ?></td>
            <td><?php the_field( 'book-published' ); ?></td>
            <td><?php the_field( 'book-isbn' ); ?></td>
            <td><?php the_field( 'book-sales' ); ?></td>
    <?php endwhile;
    echo '</table>';
} ?>

If I try to edit the array in the second block (below) and add an orderby to that, it appears to kill the first block. I just get empty tables with headings but no posts.

    // Define the query
    $args = array(
        'post_type' => 'fiction',
        'booktype' => $term->slug
    $query = new WP_Query( $args );

What else can I try?

, , , , Adoptable 8 months 0 Answers 50 views 0

Leave an answer