Jacksonkr
Jacksonkr

Reputation: 32247

wordpress orderby=rand not working

$hpPromo = new WP_Query(array('post_type' => 'homepage_promo', 'orderby' => 'rand'));
print_r($hpPromo->posts);

Every time the array is the exact same order. Why aren't my posts randomizing? Is it because I'm using a custom post_type? Please advise.

** EDIT **

In the meantime I'm doing this the only way I know how (inefficient). By all means please post an answer better than this one (for the sake of developers everywhere!)

$hpPromo = new WP_Query(array('post_type' => 'homepage_promo', 'orderby' => 'rand'));
$count = count($hpPromo->posts);
$posts = (array)$hpPromo->posts;
$promo_id = $posts[rand(0, $count-1)]->ID;
wp_reset_query();
$hpPromo = new WP_Query(array('post_type' => 'homepage_promo', 'p' => $promo_id));
$hpPromo->the_post();
the_content();

Upvotes: 0

Views: 4913

Answers (1)

Amit Deo
Amit Deo

Reputation: 364

Try removing filters which might be interfering with orderby query.

remove_all_filters('posts_orderby');
$hpPromo = new WP_Query(array('post_type' => 'homepage_promo', 'orderby' => 'rand'));
print_r($hpPromo->posts);

Upvotes: 14

Related Questions