0

I'm trying to get related posts by taxonomy term. So a post tagged to 'London' would have related posts tagged to London. The code I have works if the post is tagged to a single taxonomy term only - in this case a single Location (entry_location is the taxonomy). But if I tag it to more than one (eg London and Paris), it returns no results. How do I make it accept multiple tax terms and display results from both?

This is what I have so far. It works for posts tagged with one tax term only.

<?php
$this_post = $post->ID;
$query = new WP_Query(array(
    'post_type' => 'dir_entry', 
    'posts_per_page' => 10, 
    'orderby' => 'date', 
    'order' => 'DESC', 
    'post__not_in' => array($this_post), 
    'entry_location' => get_the_term_list( $post->ID, 'entry_location' ))
);
while ($query->have_posts()) : $query->the_post();
?>
<li class="large-6 columns">
    <a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a>
</li>

<?php endwhile; wp_reset_query(); ?>

Thanks for any advice.

2

I honestly don't see how that works at all since get_the_term_list returns an HTML string.

First, you need get_the_terms and wp_list_pluck.

Second, you need a tax_query. That {tax} = {term} pattern is deprecated.

$this_post = $post->ID;
$args = array(
    'post_type' => 'dir_entry', 
    'posts_per_page' => 10, 
    'orderby' => 'date', 
    'order' => 'DESC', 
    'post__not_in' => array($this_post), 
  );

$terms = get_the_terms($this_post,'post_tag');
if (!is_wp_error($terms)) {
  $terms = wp_list_pluck($terms,'term_id');
  $args['tax_query'] = array(
    array(
      'taxonomy' => 'post_tag',
      'field' => 'id',
      'terms' => array_values($terms)
    )
  );
  $query = new WP_Query($args);
}  

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.