WP Query Post Type with same Taxonomy name

Probably you are doing it wrong.

When you need do have a one to many relation (one author has many books) taxonomy is not best way.

Also, according to WordPress structure, naming a taxonomy and and a post in same way is not a very reliable way.

Just for example thinks if two authors are homonyms: having two authors both named “John Smith” is perfectly normal, in that case sure WordPress will assign unique slug to both taxonomy term and post slug, but for you will be hard assign right taxonomy terms on post creation.

Best way is to create a custom field for the book post type, that you can name ‘author_id’ and where during book post creation you insert the righr post id, after that, in the book page you can use:

$author_id = get_post_meta( $post->ID, 'author_id', true );
$author_post = get_post($author_id);

Sure this is not very elegant solution, but creating a custom metabox to set the meta field that show a dropdown of author post, is easy and will be elegant and pretty to see.

If you need help on creating the metabox, look at questions tagged metabox in this site.

As alternative you can also consider the well known plugin Post 2 Posts that will do the work for you.


To just answer your question, your second code block is almost right, working version (version that should work) is:

global $post;
$bookauthor = wp_get_post_terms( $post->ID, 'author' );
if ( ! empty($bookauthor) ) {
  $slug = array_shift( $bookauthor );
  $custom_query = new WP_Query( array( 'post_type' => 'author','name' => $slug->slug ) );
  // here your loop
  while ( $custom_query->have_posts() ) { $custom_query->the_post();
     // here post output
  }
  wp_reset_postdata();
}

This because IIRC wp_get_post_terms return an array using term ids as array keys.

But, as already said, I don’t think this is the right way to do it.