Getting the same post on my related post

Question

I am displaying the related products on my single.php page.

I am getting two issues.

  1. When I am on a single page I am getting the same post on my related post.
  2. I have to show the max 4 post on my related section. If I have 3 posts related to the same category then display only 3

I tried the below code.

$post_id = get_the_ID();
    $cat_ids = array();
    $categories = get_the_category($post_id);
    if(!empty($categories) && is_wp_error($categories)):
        foreach ($categories as $category):
            array_push($cat_ids, $category->term_id);
        endforeach;
    endif;
    $current_post_type = get_post_type($post_id);
    $query_args = array( 
        'taxonomy' => 'blogs_cat',
        'category__in'   => $cat_ids,
        'post_type'      => $current_post_type,
        'post_not_in'    => array($post_id),
        'posts_per_page'  => '4',
        'order' => 'DEC',
     );
    $related_cats_post = new WP_Query( $query_args );
    if($related_cats_post->have_posts()):
        echo '<div class="relatedPostWrapper"><ul>';
         while($related_cats_post->have_posts()): $related_cats_post->the_post();
          echo '<li>
                    <a href="'.get_permalink($related_cats_post->ID).'">
                        <div class="d-table">
                            <div class="relatedpost-img d-table-cell">
                            <img src="'.get_the_post_thumbnail_url($related_cats_post->ID).'">
                            </div>
                            <div class="relatedpost-title d-table-cell">
                                 '.get_the_title($related_cats_post->ID).'
                            </div>
                        </div>
                    </a>
                </li>';
        endwhile;
        echo '</ul></div>';
        wp_reset_postdata();
     endif;
0
user9437856 4 months 0 Answers 24 views 0

Leave an answer