免费《新手做网站视频教程》,在线观看,如果你想从零开始自己做网站,点击开始吧!

WordPress 内置函数 get_posts() 详解

  1. 首页
  2. »
  3. 图文教程
  4. »
  5. WordPress建站教程
  6. »
  7. WordPress 内置函数 get_posts() 详解

文章目录

WordPress提供内置函数 get_posts() ,用于获取多个文章,它的用法也非常简单。先看下下面的demo:

demo:获取随机文章

<ul>
<?php
// 获取随机文章
$args = array( 'numberposts' => 3, 'orderby' => 'rand', 'post_status' => 'publish' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li><p class="limit" style="width: 75%"><a href="<?php the_permalink();?>" target="_blank"><?php the_title()?></a></p><span style="float:right; font-size: 10px;"><?php the_views();?>人 阅读过</span></li>
<?php endforeach; wp_reset_query();?>
</ul>

get_posts() 函数详解

上面的demo是获取全站随机文章, $args 变量保存参数,具体为:

$args = array( 'numberposts' => 3, 'orderby' => 'rand', 'post_status' => 'publish' );

 

get_posts() 函数参数

$args = array(

//需要提取的文章数
'numberposts' => 10,

//以第几篇文章为起始位置
'offset' => 0,

//分类的ID,多个用逗号将分类编号隔开,或传递编号数组,可指定多个分类编号。
//大部分 CMS 使用该函数的重点。
'category' => ,

//排序规则(请看备注)
'orderby' => 'post_date',

//升序、降序 'ASC' —— 升序 (低到高) 'DESC' —— 降序 (高到底)
'order' => 'DESC',

//要显示文章的ID
'include' => ,

//要排除文章的ID
'exclude' => ,

//自定义字段名称
'meta_key' => ,
//自定义字段的值,配合上一个参数,来选择显示符合自定义字段数值的文章。
'meta_value' => ,

//post(日志)——默认,page(页面),
//attachment(附件),any —— (所有)
'post_type' => 'post',

//文章的 mime 类型
'post_mime_type' => ,

//要显示文章的父级 ID
'post_parent' => ,

//文章状态
'post_status' => 'publish' );

 

注释-排序规则:

‘author’ —— 按作者数值编号排序
‘category’ —— 按类别数值编号排序
‘content’ —— 按内容排序
‘date’ —— 按创建日期排序
‘ID’ —— 按文章编号排序
‘menu_order’ —— 按菜单顺序排序。仅页面可用。
‘mime_type’ —— 按MIME类型排序。仅附件可用。
‘modified’ —— 按最后修改时间排序。
‘name’ —— 按存根排序。
‘parent’ —— 按父级ID排序
‘password’ —— 按密码排序
‘rand’ —— 任意排序结果
‘status’ —— 按状态排序
‘title’ —— 按标题排序
‘type’ —— 按类型排序

推荐阅读

联系我