0

I have a custom post type called as books with taxonomy named as genre. Inside the genre there are a number of terms such as horror, romance,comedy`, etc.

I want to display them in the archive page, grouped by each terms. So I use Chip Bennet's fantastic code.

However, I have problem with the sorting.

The code sorts the terms according to its alphabetical names, and the posts according to the recentness. So it appears like this:

  • Comedy
    • Newest book
    • Not so new book
    • Old book
  • Horror
    • etc the same: newest - not new - old
  • Romance
  • Sci-fi

Meanwhile, I need it to be sorted differently. I want to sort the terms according to the tag_ID, and the book list according to its alphabetical name. So it should look like this:

  • Sci-fi (tag_ID number 1)
    • A
    • B
    • C
    • etc
  • Romance (tag_ID number 2)
  • Comedy (tag_ID number 3)
  • Horror (tag_ID number 4)

I tried to mess with the query, so it looks like this

$member_group_query = new WP_Query( array(
    'post_type' => 'member',
    'orderby ' => 'name', // sort the books alphabetically
    'tax_query' => array(
        array(
            'taxonomy' => 'member_group',
            'field' => 'slug',
            'terms' => array( $member_group_term->slug ),
            'orderby ' => 'ID', // sort the genre according to its ID
            'operator' => 'IN'
        )
    )
) );

But nothing changes. I checked Wordpress Codex on WP_Query to make sure but still no avail. Any help?

1

I think you need first to sort the genre terms in the other query:

$genres = get_terms( 'genre', 'orderby=term_id' );

And then on the posts query for each genre (like Chip Bennet's approach):

$member_group_query = new WP_Query( array(
    'post_type' => 'member',
    'orderby' => 'name',
    'tax_query' => array(
        array(
            'taxonomy' => 'member_group',
            'field' => 'slug',
            'terms' => array( $member_group_term->slug ),
            'operator' => 'IN'
        )
    )
) );
4
  • Oh so that's where you sort the genre. Thanks! It works for the genre, but I can't still sort the books... it's still sorted by its newness rather than alphabetically. Oddly 'orderby' => 'rand' works but not 'orderby' => 'name'... – deathlock Jun 21 '17 at 15:05
  • and if you try 'orderby' => 'title' instead? – dbeja Jun 21 '17 at 15:09
  • Okay, curiously it works with 'orderby' => 'title' and 'order' => 'ASC'. Really odd. Thanks @dbeja! – deathlock Jun 21 '17 at 15:25
  • when you order by name, you're ordering by slug. I don't know if it's related or not. but now it's working :) – dbeja Jun 21 '17 at 15:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.