WordPress: Related Posts by Tags, but in the Same Categories

I’m using the script below to get related posts by tags, but noticed that if I have a picture of a bird tagged white and a table also tagged white, the table will show up in the related posts section of the bird. Is there a way to only get posts that match at least one of the categories, so bird and table won’t be related, unless they share one category?

I tried setting an category__in array inside $args, but no luck!

<?php
  $tags = wp_get_post_tags($post->ID);
  if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;

$args=array(
    'tag__in' => $tag_ids,
    'post__not_in' => array($post->ID),
    'showposts'=>6, // Number of related posts that will be shown.
    'caller_get_posts'=>1
);
$my_query = new wp_query($args);
if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) {
        $my_query->the_post();
    ?>

    <?php if ( get_post_meta($post->ID, 'Image', true) ) { ?>
        <a style="text-decoration: none;" href="<?php the_permalink(); ?>">
            <img style="max-height: 125px; margin: 15px 10px; vertical-align: middle;" src="<?php bloginfo('template_directory'); ?>/scripts/timthumb.php?src=<?php echo get_post_meta($post->ID, "Image", $single = true); ?>&w=125&zc=1" alt="" />
        </a>
    <?php } ?>      

    <?php
    }
}
  }
?>

Related posts

Leave a Reply

1 comment

  1. It seems that WordPress don’t create multiple join of the wp_term_taxonomy and wp_term_relationships tables which is strange!
    Anyway, a quick hack (not efficient) is after getting the posts based on the tags, compare the original post categories with the returned posts’ ones:

    $tags = wp_get_post_tags($post->ID);
    $cats = wp_get_post_categories($post->ID);
    
    ...
    
    $my_query->the_post();
    $resCats = wp_get_post_categories($post->ID);
    $resArr = array_diff($resCats, $cats);
    if(count($resArr) != count($resCats)) {
    

    I’ll dig deeper in the query_posts method and maybe writing a plug-in about this when have time.