• Resolved cyndimarie

    (@cyndimarie)


    This code is hooked beneath each post. It displays the thumbnail and title of 4 posts from the same category as the preceding post.

    It works as long as the post is only assigned to one category, but if it is in two it shows 4 posts from each category (thus totaling 8).

    How would I change this function to only include the 4 posts from one category? I don’t care which of the 2 categories, it could just choose the first one, or it could exclude by category slug or ID….

    /** You may also like */
    function my_related_posts() {
    if (is_single()) {
    	global $post;
    	$current_post = $post->ID;
    	$categories = get_the_category();
    foreach ($categories as $category) :
    	?>
    <div class="featured-posts-box"><div class="my-recent-posts"><h4>More articles in <span style="font-style:italic;color:#a5d2d8;"><?php
    $category = get_the_category();
    echo $category[0]->cat_name;
    ?></span></h4><ul class="top-featured-image">
    	<?php
    	$posts = get_posts('numberposts=4&orderby=rand&category='. $category->term_id . '&exclude=' . $current_post);
    foreach($posts as $post) :
    	?>
    <li  class="top-featured-image"><span><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></span> <?php if ( has_post_thumbnail()) : the_post_thumbnail('thumbnail'); endif; ?></li>
    	<?php endforeach; ?><?php endforeach; ?>
    </ul>
    </div>
    </div>
    	<?php
    		}
    	wp_reset_query();
    }
Viewing 2 replies - 1 through 2 (of 2 total)
  • Try changing this:

    <?php endforeach; ?><?php endforeach; ?>

    to this:

    <?php endforeach; ?><?php break; ?><?php endforeach; ?>

    That should exit the loop after the first category.

    Thread Starter cyndimarie

    (@cyndimarie)

    Thank you that did the trick!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Change function to only pull from one category’ is closed to new replies.