WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] Random Posts from same category

[Resolved] Random Posts from same category

  • Hey gang,
    I’m working on a script that will pull recent posts in the same category. I’ve got it working, but it’s pulling the most recent 6 posts when I’d really like to be pulling 6 random posts from the category… I’ve spent hours trying to resolve this but alas my PHP skills aren’t awesome… any help would be GREATLY appreciated.

    Here’s what I’ve got:

    <?php
    	// get other posts from this category only as related posts //
    	$backup = $post;  // backup the current object
        $categories = get_the_category($post->ID);
        if ($categories) {
            $category_ids = array();
            foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
    
            $args = array (
                'category__in' => $category_ids,
                'post__not_in' => array($post->ID),
                'showposts'=>6, // Number of related posts that will be shown.
                'caller_get_posts'=>1
            );
    
            $my_query = new wp_query($args);
            if( $my_query->have_posts() ) {
                while ($my_query->have_posts()) : $my_query->the_post();
          ?>
                    <div>
                    <?php $image = get_post_meta($post->ID, 'article_image', true); ?>
                    <a href="<?php the_permalink($post->ID); ?>"><img src="<?php echo $image; ?>" alt="<?php the_title(); ?>" style="height: 90px; width: 90px; float: left; margin: 8px 8px 0px 0px; border: 1px black solid; padding: 0px;"></a>
                    </div>
    			<?php
    		endwhile;
    	  }
    	  $post = $backup;  // copy it back
    	  wp_reset_query(); // to use the original query again
    	}
    	?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • esmi

    @esmi

    Forum Moderator

    Try:

    $args = array (
                'category__in' => $category_ids,
                'post__not_in' => array($post->ID),
                'posts_per_page'=>6, // Number of related posts that will be shown.
                'orderby' = > 'rand',
                'caller_get_posts'=>1
            );

    Thanks esmi! That worked like a charm! … feel a little stupid for not trying that beforehand, but thank you so much for the help!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘[Resolved] Random Posts from same category’ is closed to new replies.