I would like to show 8 random posts on single page from same category.

    global $post;
    $categories = get_the_category();
    foreach ($categories as $category) :
    $args = array( 'numberposts' => 8, 'orderby' => 'rand', 'category' => $category->term_id);
    $rand_posts = get_posts( $args );
    foreach( $rand_posts as $post ) :

    <li><?php the_post_thumbnail(); ?><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><span><?php the_title(); ?></span></a></li>
    <?php endforeach; ?>
    <?php endforeach; ?>

..but if the post has 2 or more categories it lists 16/24/32 posts. I hope anyone can help to me. Thanks!

  • 1
    you're iterating over each category and fetching 8 posts for each, what results do you want if the post has more than a single category?
    – Milo
    Commented Jan 7, 2013 at 16:20

1 Answer 1


This happens because you use a foreach loop on post categories. You can display random posts from the first returned category by getting rid of the foreach loop and using $categories[0]->term_id as your category in query args.

You can also try to grab all the category IDs for all your categories and include them as comma separated list. This will return 8 random posts from all categories associated with your post. Read more in the 'Paramaters' section of get_posts function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.