2
votes

on my main page I'd like to be able to make a query of random posts that are consistent throughout a pagination. i have found sevral explanations that uses 'wp_query', but i am looking for a solution that will help me with 'get_posts'.

this is the code i got so far:

foreach ( $categories as $category ) {
    global $post;
                $myposts = get_posts(array(
                    'post_type' => 'portfolio', 
                    'orderby'     => 'rand',
                    'posts_per_page' => 1,
                    'numberposts'   => -1, // get all posts.
                    'tax_query'     => array(
                        array(
                            'taxonomy'  => 'portfolio_categories',
                            'field'     => 'id',
                            'terms'     => $category->cat_ID
                        )

                    )
                ));
                foreach ( $myposts as $post ){
                    setup_postdata( $post );

// stuff of posts
}
            wp_reset_postdata(); }
1
That's not going to work. You would have to make your random query only once on the initial page load and then store the results in for example a session. Then you can use these stored results in your pagination.jeroen
thank you for the comment. do you have any example ?user3003106

1 Answers

1
votes

get_posts() utilizes the WP_Query() class behind the scenes. Therefore, anything you can do with WP_Query(), you can do with get_posts(), with few documented exceptions.

While you can easily handle this with via the posts_orderby filter, as of Wordpress 4.5, the WP_Query() class supports the use of the built-in MySQL RAND(n) seed value, which will allow you to pull a consistent set of random posts.

As an example:

$posts = get_posts(array(
    'post_type' => 'portfolio',
    'orderby'     => 'rand(1234)',
    'posts_per_page' => 1,
    'numberposts'   => -1, // get all posts.
    'tax_query'     => array(
        array(
            'taxonomy'  => 'portfolio_categories',
            'field'     => 'id',
            'terms'     => $category->cat_ID
        )

    )
));

As long as 1234 is passed on each query, the same set of random posts will be returned, therefore allowing you to easily paginate. If you pass a new value (i.e. 5678), the random set will change. The thought process here is to store a different random integer for each user session.

For more information on how the MySQL RAND(n) function works, see the docs.