Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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);
}  
share|improve this answer
    
That works perfectly, thank you –  Xav Jul 21 '13 at 11:32
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.