WP-Query order by rand具有自定义帖子类型和自定义分类法返回有序输出

时间:2015-11-19 10:55:05

标签: php wordpress wp-query

我正在尝试从自定义帖子类型和自定义分类中提取帖子。 我使用以下查询来实现:

$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,
            )
        ),
    )
);

当我使用$ the_query-> request

print_r($the_query->request);

打印SQL我得到以下输出:

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()

似乎合法,对吗?我甚至去了数据库本身并尝试了查询,它与随机化完美配合,并且每次都以随机顺序返回帖子。

First try with the query Second try with the query

但出于某种原因,当我试图采摘id的数组时:

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

我每次都以相同的顺序获取数组:

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

当我试图将WP_Query放入循环时:

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

每次都以有组织的顺序返回帖子。

知道如何让WP_Query以随机顺序返回帖子,而不应用外部函数吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

检查您是否安装了可能导致orderby = rand功能无效的Post Types Order插件。此外,如果您在WP引擎上运行您的站点,则报告已在服务器上禁用此功能,并且需要启用此功能。

修改 检查this site explaining where to find that option,无论如何这种随机化是性能杀手,但我认为你意识到了