Skip to content

Instantly share code, notes, and snippets.

@fikrirasyid
Created October 5, 2014 10:21
Show Gist options
  • Save fikrirasyid/215764f7812a08e8955e to your computer and use it in GitHub Desktop.
Save fikrirasyid/215764f7812a08e8955e to your computer and use it in GitHub Desktop.
Randomizing WP_Query's Posts Order
/**
* Assuming you want 8 latest posts and excluding sticky posts
*/
$posts_args = array(
'ignore_sticky_posts' => true,
'posts_per_page' => 8
);
$posts = new WP_Query( $posts_args );
if( $posts->have_posts() ){
/**
* Convert the posts' object into array
*/
$original_posts = (array) $posts->posts;
/**
* Shuffle the array of posts
*/
shuffle( $original_posts );
/**
* Convert the shuffled array of posts into object
* Hat tip to Edson Medina for this simple trick: http://stackoverflow.com/questions/1869091/convert-array-to-object-php/9895734#9895734
*/
$shuffled_posts = json_decode( json_encode( $original_posts ), FALSE );
/**
* Overwrite the WP_Query's post data using the shuffled one
*/
$posts->posts = $shuffled_posts;
/**
* Loop the posts cdata
*/
while ( $posts->have_posts() ) {
$posts->the_post();
/**
* Get the content template
*/
get_template_part( 'content' );
}
} else {
/**
* Display no posts found state here
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment