Order custom posts by taxonomy?

I believe you need a tax_query like the following from the Codex:

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => 'people',
            'field' => 'slug',
            'terms' => 'bob'
        )
    )
);
$query = new WP_Query( $args );

In your case that would look something like:

$args = array(
  'post_type'     =>  'books',
  'tax_query' => array(
     array(
       'taxonomy' => 'book_category',
       'field' => 'slug',
       'terms' => array('step2-prepare','step3-find')
     )
  ),
  'posts_per_page'    =>  -1,
  'order'             =>  'ASC',
  'orderby'           =>  'ID'
);
$the_query = new WP_Query( $args );

I am guessing at the taxonomy slugs–‘step2-prepare’,’step3-find’ — but I think the syntax is correct. Untested as I don’t have your taxonomy and posts in my database.

That should “ONLY the posts that are in the category called “Step2: Prepare” or “Step3: Find”.”

You can’t ORDER BY a category/taxonomy– Using wp_query is it possible to orderby taxonomy? What you have to do is Loop over the posts, create a new sorted array, then Loop over that to display the posts. Doing so could make pagination a bit weird, so be careful. This is very rough and without your taxonomy and posts it is hard to test anything but…

$sorted = array();
foreach ($the_query as $tq) {
  $terms = wp_get_post_terms( $tq->ID, 'book_category');
  $sorted[$terms[0]->slug] = $tq;
}

However, there are problems with that. The first that comes to mind is that if you have multiple terms you have to pick one of them or insert your post multiple times in the $sorted array.

Leave a Comment