WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Change function to only pull from one category (3 posts)

  1. cyndimarie
    Member
    Posted 1 year ago #

    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();
    }
  2. vtxyzzy
    Member
    Posted 1 year ago #

    Try changing this:

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

    to this:

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

    That should exit the loop after the first category.

  3. cyndimarie
    Member
    Posted 1 year ago #

    Thank you that did the trick!

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.