Question

In my wordpress installation, I have a custom taxonomy event-categories which is mapped to custom post type event.

In my single post display page, I need to list all posts which is posted in same event-categories of the current post. How can I write a wp query for this?

Screen-shot for my custom taxonomy in custom post.

enter image description here

Now tried like this get_the_terms(the_ID(), 'event-categories').

So I got all term_taxonomy_ids related to the single post. Next how can I get all posts which have these term_taxonomy_id.

Was it helpful?

Solution

This would be about the most basic query to solve your problem.

$term_tax_ids = get_the_terms(get_the_ID(), 'event-categories');
$terms = array();

foreach($term_tax_ids as $term_tax_id) {
  array_push($terms, $term_tax_id->term_id);
}

$args = array(
  'post_type' => 'event',
  'posts_per_page' => 5,
  'tax_query' => array(
    array(
      'taxonomy' => 'event-categories',
      'field' => 'id',
      'terms' => $terms,
      'operator' => 'IN',
    )
  )
);

$query = new WP_Query( $args );

while ( $query->have_posts() ) {
  $query->the_post();
  echo '<div class="related_single">' . get_the_post_thumbnail();
  echo '<div class="related_title"><a href="' . get_permalink() . '">' . get_the_title() . '</a></div></div>';
}

You should really read the Codex, it has literally everything you could ever want to know about queries

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top