'Related posts by category

I am trying to display automatically a number of related posts by category under the content of every post page.

// Related Posts by 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);
        endforeach;
    endif;

    $current_post_type = get_post_type($post_id);

    $query_args = array( 
        'category__in'   => $cat_ids,
        'post_type'      => $current_post_type,
        'post__not_in'    => array($post_id),
        'posts_per_page'  => '4',
     );

    $related_cats_post = new WP_Query( $query_args );

    if($related_cats_post->have_posts()):
         while($related_cats_post->have_posts()): $related_cats_post->the_post();
             return '<ul>
                       <li>
                          <a href="'.get_permalink().'">'.get_the_post_thumbnail($post->ID, array(150, 100)).get_the_title().'</a>
                      </li>
                    </ul>';             
         endwhile;

        // Restore Original Post Data
        wp_reset_postdata();
     endif;
}

Then I successfully add it after the post content:

// Add After Content
function related_posts_after($content) {
  if ( is_single() ) {
     ob_start();    
     $aftercontent = example_cats_related_post();
     $fullcontent = $content.$aftercontent;
     return $fullcontent;
  } else {
     return $content;
  }
}
add_filter('the_content', 'related_posts_after');

The problem is that only one related post is displayed and not the number in the arguments (posts_per_page). I'd tried different modifications but with no result. Thank you in advance!



Solution 1:[1]

The issue is in your while.

You can't use a return there as a return exits. Needs to be echo or close/open PHP.

return '<ul>
                       <li>
                          <a href="'.get_permalink().'">'.get_the_post_thumbnail($post->ID, array(150, 100)).get_the_title().'</a>
                      </li>
                    </ul>';  

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bazdin