WP_Query按" rand"排序和"名称"?

时间:2016-09-01 07:36:08

标签: wordpress

我正在使用Wordpress和我主页上的帖子,我希望他们随机和按名称订购。我的意思是,我想每次在我的主页上显示不同的帖子,但是按照他们的名字排序。我从我的主题文件中更改了WP_Query args,如下所示,但它没有用。由于我无法理解的原因,我得到了无关的结果。

void Auth_SessionAuthenticated(object sender, SessionAuthenticatedEventArgs e)
{
   string boxAccessToken = e.Session.AccessToken;
   string boxRefreshToken = e.Session.RefreshToken;
}

有没有办法让这成为可能?

P.S。老实说,我不喜欢那些无可非议地回答问题的人。如果我在互联网上找到解决方案,我不会问这个问题。如果您有合理的理由,请警告我或编辑我的帖子,而不是盲目地低估它。

1 个答案:

答案 0 :(得分:2)

As documented:

  

orderby( string | array ) - 按参数对检索的帖子进行排序。默认为'日期(post_date)'。可以传递一个或多个选项。

所以:

$args = array(
    'orderby' => array( 'rand', 'name' ),
    'order'   => 'DESC',
);

但我不认为这会让你得到你想要的结果。您很可能只需使用rand posts_per_page设置即可获得所需的帖子数量。获取所有帖子,然后按名称对这些帖子进行排序。

示例:

$args = array(
    'orderby' => 'rand',
);
// get X random posts (10 by default)
$result = new WP_query( $args );

// sort these posts by post_title
usort( $result->posts, function($a, $b) {
    if ( $a->post_title == $b->post_title )
        return 0;
    return ($a->post_title < $b->post_title) ? -1 : 1;
} );

// Start the loop with posts from the result.
while ( $result->have_posts() ) : $result->the_post();
    // do your stuff in the loop
}
相关问题