1

I have 3 categories: A, B, C. A is having around 1000 posts, B has around 300 posts and C has 50 posts. When I query for 5 posts, ordered randomly. I get mostly posts from A category.

How can get mixed category random posts like 3 from A, 1 from B and 1 from C?

1

I whipped this up:

echo '<ul>';
    the_random_posts();
echo '</ul>';

/**
 * Send random posts to the browser (STDOUT).
 */
function the_random_posts() {

    // Use your own category ids.
    $random_posts = array_merge(
        get_random_posts( 31, 3 ),
        get_random_posts( 11, 1 ),
        get_random_posts( 24, 1 )
    );

    foreach ( $random_posts as $post ) {
        // Change this line to code you want to output.
        printf( '<li><a href="%s">%s</a></li>', get_permalink( $post->ID ), get_the_title( $post->ID ) );
    }
}

/**
 * Get $post_count random posts from $category_id.
 *
 * @param int $post_count Number of random posts to retrieve.
 * @param int $category_id ID of the category.
 */
function get_random_posts( $category_id, $post_count ) {

    $posts = get_posts( array(
        'posts_per_page' => $post_count,
        'orderby'        => 'rand',
        'cat'            => $category_id,
        'post_status'    => 'publish',
    ) );

    return $posts;
}

If any posts are in 2 or more of the selected categories there is a chance that a post will be repeated (like a post that is in both category A and category B). A static variable with an array of previously retrieved post might fix that.

This algorithm prints the posts in the order they were called.

get_random_posts( 31, 3 ), // First, 3 random posts from Category A
get_random_posts( 11, 1 ), // Then,  1 random post  from Category B
get_random_posts( 24, 1 )  // Then,  1 random post  from Category C

If you want a random list, shuffle $random_posts.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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