lunule
2/8/2015 - 9:54 PM

WordPress | Randomize order of posts resulted from WP_Query().

WordPress | Randomize order of posts resulted from WP_Query().

<?php

/**
* 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
	 */
}