Display related posts within the current posts category


This code has been referenced many times throughout WP forums and never seems to have an answer that works.

The following code seemed to work and displayed a list of posts within the same category when I visited a post. However, after testing when I removed the post from the category and moved other posts to different categories it failed. It had no effect, and all posts continued to display regardless of category, think the first section related to associated category is incorrect. Any help would be appreciated. The objective is to show posts in the same category.

function example_cats_related_post() {

$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);

$current_post_type = get_post_type($post_id);
$query_args = array( 

    'category__in'   => $cat_ids,
    'post_type'      => $current_post_type,
    'post__not_in'  => array(get_the_ID()),     // Exclude current post
    'posts_per_page'  => '100',     // How many items to display
    'no_found_rows'  => true,      // We don't ned pagination so this speeds up the query
    'order'     => 'ASC',       // Ascending order
    'orderby' => 'menu_order title' // Order by menu fallback title

$related_cats_post = new WP_Query( $query_args );

     while($related_cats_post->have_posts()): $related_cats_post->the_post(); ?>
        <ul class="related-group">
                <a href="<?php the_permalink(); ?>">
                <?php the_field('chain_number'); ?>
    <?php endwhile;

    // Restore original Post Data


Martin 4 months 0 Answers 16 views 0

Leave an answer