在WordPress中显示基于两个orderby值的查询帖子

时间:2016-11-03 作者:Jay Bro

我一直在尝试显示热门帖子(基于视图计数),并在中使用数组随机获取它们orderby 但它似乎不起作用。我希望它们随机显示的原因是,我不希望同一篇文章重复显示给new&;随着景观数量的自然增加,游客不断增加。

以下是我尝试的代码:

$popularpost = new WP_Query(
    array(
        \'category\'          => \'comedy\',
        \'posts_per_page\'    =>  4,
        \'meta_key\'          => \'post_views_count\',
        \'orderby\'           => array (\'meta_value_num\', \'rand\'),   //this is the one I want both rand & meta_value_num to retrieve
        \'order\'             => \'DESC\'
    ) 
);

while ( $popularpost->have_posts() ) : $popularpost->the_post();
    the_permalink();
    the_title();
    if ( has_post_thumbnail() ):
        the_permalink(\' \');the_title();
        the_post_thumbnail();
    endif;
    the_excerpt(); // echo the excerpt
endwhile;
一切正常,只是它不会随机回迁。始终显示相同的帖子。

1 个回复
最合适的回答,由SO网友:jgraup 整理而成

我想你可能很容易根据视图数获得前25名,然后从列表中随机选择4名。

下面是一个易于测试的查询,但您希望将其替换为post_views_count 查询并删除任何rand 订货人。

// get top 25
$posts = get_posts( array (
    \'post_type\'      => array ( \'post\' ),
    \'posts_per_page\' => 25,
    \'fields\'         => \'ids\',
) );

// randomize the top 25
shuffle( $posts );

// pull to first 4 items
$posts = array_slice( $posts, 0, 4 );

// show the results
echo "<pre>";
foreach ( $posts as $post_id ) {
    echo get_the_title( $post_id ) . PHP_EOL;
}
使用您的查询:

// query the top posts
$popularpost = new WP_Query(
    array(
        \'category\'          => \'comedy\',
        \'posts_per_page\'    =>  25, // top 25
        \'meta_key\'          => \'post_views_count\',
        \'orderby\'           => array (\'meta_value_num\'),
        \'order\'             => \'DESC\'
    )
);

// randomize the items
shuffle($popularpost->posts);

// limit the the number of posts
$popularpost->posts = array_slice( $popularpost->posts, 4); // random 4 posts

// output
while ( $popularpost->have_posts() ) : $popularpost->the_post();
    the_permalink();
    the_title();
    if ( has_post_thumbnail() ):
        the_permalink(\' \');the_title();
        the_post_thumbnail();
    endif;
    the_excerpt(); // echo the excerpt
endwhile;

相关推荐