Forked from fikrirasyid/Randomizing WP_Query's Posts Order
Last active
November 5, 2016 04:54
-
-
Save lunule/d15243ab8c156550b3b4 to your computer and use it in GitHub Desktop.
WordPress | Randomize order of posts resulted from WP_Query().
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment