I'm creating an authors site. I'm using a custom post type (Books) to display books. I'm using another custom post type (Reviews) to display reviews on the same page as the corresponding book. I'm sorting books and reviews with a custom taxonomy, with terms such as book1, book2, etc.

On each single book page (single-books.php), I'm running a second query to display the reviews. So far so good. The problem is how to display ONLY the reviews with the same term as the current book.

How can I get the term from the first query and then run it in the next query?


If I understand correctly, the book and the reviews share same taxonomy.

Then is just a matter of get the taxonomy term for the book in the single-books.php, save it in a variable and then run a query using that variable for the 'tax_query':

if ( have_posts() ) {

  // get the term for the current book and save in a variable
  $book_terms = get_the_terms( get_the_ID(), 'your_custom_taxonomy' );
  $book_term = ! empty( $book_terms ) ? array_shift( $book_terms ) : FALSE;

  // loop code for the book goes here


if ( $book_term ) { // if we get the term for current book...
  // second query
  $args = array(
    'post_type' => 'review',
    'tax_query' => array(
         'taxonomy' => 'your_custom_taxonomy',
         'terms' => array( $book_term->term_id )
  $reviews = new WP_Query( $args );

  // loop code for review goes here
  • Fantastic! Works perfectly. Thank you. I had tried pretty much the same but without the line with $book_term = ! empty... Can you explain what that line actually does? – Dropshotdragon Apr 2 '14 at 8:44

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.