I have a Projects custom post type with a custom taxonomy of Services. Each project can have multiple services ticked. On the project page I am using the following code to pull back related projects
<?php
//for in the loop, display all "content", regardless of post_type,
//that have the same custom taxonomy (e.g. genre) terms as the current post
$backup = $post; // backup the current object
$found_none = '';
$taxonomy = 'services';// e.g. post_tag, category, custom taxonomy
$param_type = 'services'; // e.g. tag__in, category__in, but genre__in will NOT work
$post_types = get_post_types( array('public' => true), 'names' );
$tax_args=array('orderby' => 'none');
$tags = wp_get_post_terms( $post->ID , $taxonomy, $tax_args);
if ($tags) {
echo "<section class='divide'>";
echo "<div class='container'>";
echo "<h2 class='no-border'>Related projects</h2>";
echo "<ul class='portfolio'>";
foreach ($tags as $tag) {
$args=array(
"$param_type" => $tag->slug,
'post__not_in' => array($post->ID),
'post_type' => $post_types,
'showposts'=>3,
'caller_get_posts'=>1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
?>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li>
<a href="<?php the_permalink(); ?>">
<img src="<?php $src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 315,225 ), true, '' ); echo $src[0]; ?>" />
<h3><?php the_title(); ?></h3>
<?php the_field('client'); ?>
</a>
</li>
<?php $found_none = '';
endwhile; ?>
<?php
}
}
echo '</ul>';
echo "</div>";
echo "</section>";
}
if ($found_none) {
echo $found_none;
}
$post = $backup; // copy it back
wp_reset_query(); // to use the original query again
?>
Initially it looked like it was working fine but on closer inspection if a project has more than one service then it is duplicating the posts that are pulled back.
So any tips? Is there a better way to pull back related posts (by taxonomy) and how do I stop the duplication of results?
Thanks!