WordPress 的文章查询函数 get_posts() 有个参数 orderby 指明了获取文章时的排序方式。通常我们是按照文章发布日期排序,比如 WordPress 站点首页、分类页和标签页中的文章列表。orderby 还可以是 rand,它使用 MySQL 的 RAND() 函数来确定排序参数,也就是随机排序。
随机文章代码:
$args = array( 'numberposts' => 5, 'orderby' => 'rand', 'post_status' => 'publish' ); $rand_posts = get_posts( $args );
这样就能得到随机排序(第 2 个参数)的已发布(第 3 个参数)文章中的 5 篇(第 1 个参数)。
需要特别注意的是,如果没有第 3 个参数,它可能会将草稿之类的文章也显示出来。
找到如下代码:
$args = array( 'category__in' => array( $cats[0] ), 'post__not_in' => array( $post->ID ), 'showposts' => 6, 'caller_get_posts' => 1 );
添加:'orderby' => 'rand',
添加后的代码如下:
$args = array( 'orderby' => 'rand', 'category__in' => array( $cats[0] ), 'post__not_in' => array( $post->ID ), 'showposts' => 6, 'caller_get_posts' => 1 );
文章评论