Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

<?php
    global $post;
    $categories = get_the_category();
    foreach ($categories as $category) :
    $args = array( 'numberposts' => 8, 'orderby' => 'rand', 'category' => $category->term_id);
    var_dump($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!

share|improve this question
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 Jan 7 '13 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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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