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
}
}
}
?>
It seems that WordPress don’t create multiple join of the
wp_term_taxonomy
andwp_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:
I’ll dig deeper in the
query_posts
method and maybe writing a plug-in about this when have time.