Code Samples /

Random Ordering

Out-of-the-box, Ajax Load More does not support ordering posts by random, however, it can be achieved by running a custom get_posts query to build an array of post IDs. The IDs are then passed to Ajax Load More via the post__in parameter.

functions.php
<?php
// Query ALL posts, ordered by `rand`.
$args = [
   'post_type'           => [ 'post' ],
   'orderby'             => 'rand',
   'posts_per_page'      => -1,
   'fields'              => 'ids'
];
$post_ids = get_posts( $args );
   
// Pass $post_ids array to Ajax Load More post__in parameter.
echo do_shortcode( '[ajax_load_more post__in="' . implode( ',', $post_ids ) . '" orderby="post__in"]' ); 
PHP

Note: Ordering by random is very server intensive and some hosts (e.g. WPEngine) disallow this orderby query parameter completely.


« Back to Code Samples