How to create related posts functionality for wordpress custom post type posts when one posts belongs to many categories

I need to add related posts functionality in the single page of wordpress custom post type.I have posts that belong to multiple categories and that posts are shown twice one at the top when displaying its content and also itself is shown in the related posts part.I tried with this code

<?php
        $backup = $post;  // backup the current object
        $found_none = '<h2>No related posts found!</h2>';
        $taxonomy = 'news-category';//  e.g. post_tag, category, custom taxonomy
        $param_type = 'news-category'; //  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) {
          foreach ($tags as $tag) {
            $args=array(
              "$param_type" => $tag->slug,
              'post__not_in' => array($post->ID),
              'post_type' => $post_types,
              'showposts'=>-1,
              'caller_get_posts'=>1
            );
            $my_query = null;
            $my_query = new WP_Query($args);
            if( $my_query->have_posts() ) {
              while ($my_query->have_posts()) : $my_query->the_post(); ?>
                <div class="related_post_item">
                <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>
                <div class="news_date"><?php echo get_the_date('F Y', $post->ID); ?></div>
                <?php $found_none = ''; ?>
                                </div>
            <?php  endwhile;
            }
          }
        }
        if ($found_none) {
        echo $found_none;
        }
        $post = $backup;  // copy it back
        wp_reset_query(); // to use the original query again
        ?>

It works perfectly when one category is checked per post, but I have posts that belong to multiple categories.How to detect related posts correctly when having multiple categories checked?

Related posts

1 comment

  1. Hey I found a simple solution.Tracked the Id of current post and when displaying my loop added the following code

                $exclude = $GLOBALS['current_id'];
                $args=array(
                  "$param_type" => $tag->slug,
                   'post__not_in' => array($exclude),
                  'post_type' => $post_types,
                  'showposts'=>-1,
                  'caller_get_posts'=>1
                );
    

    That’s it!!

Comments are closed.