简体   繁体   中英

WP-Query orderby rand with custom post type and custom taxonomy returns ordered output

I'm trying to pull up posts from a custom post type and a custom taxonomy. I used the following query to achieve that:

$term_list = wp_get_post_terms($post->ID, 'influencers', array("fields" => "all"));
$the_query = new WP_Query( array(
    'posts_per_page' => -1,
    'post_status' => 'publish',
    'post_type' => 'influencer',
    'orderby' => 'rand',
    'tax_query' => array(
        array(
                'taxonomy' => 'influencers',
                'field' => 'slug',
                'terms' => $term_list[0]->slug,
            )
        ),
    )
);

When i'm using $the_query->request

print_r($the_query->request);

to print the SQL i'm getting the following output:

SELECT wp_posts.* FROM wp_posts INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (47329) ) AND wp_posts.post_type = 'influencer' AND ((wp_posts.post_status = 'publish')) GROUP BY wp_posts.ID ORDER BY RAND()

Seems legit, right? I even went to the database itself and tried the query, it works perfectly with the randomization and returns the posts in a random order every time.

首先尝试查询 第二次尝试查询

But for some reason, when i'm trying to pluck the id's array:

$post_ids = wp_list_pluck( $the_query->posts, 'ID' );
print_r($post_ids);

I'm getting the array in the same order, every time:

Array ( [0] => 267133 [1] => 267137 [2] => 267139 [3] => 267141 [4] => 267143 )

When i'm trying to put the WP_Query in a loop:

while ( $the_query->have_posts() ) {
    $the_query->the_post();
    //code to display loop
}
wp_reset_postdata();

It returns the posts in an organized order, every time as well.

Any idea how to make WP_Query to return the posts in randomized order, without applying outside functions?

Thanks!

Check if you don´t have Post Types Order plugin installed that might cause orderby=rand function not working. Also if you are running your site on WP Engine, it has been reported, that this function is disabled on server and needs to be enabled.

EDIT: check this site explaining where to find that option , anyway this randomization is performance killer, but I think you realise that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM