Heim  >  Artikel  >  Backend-Entwicklung  >  WordPress开发中用于获取近期文章的PHP函数使用解析_php技巧

WordPress开发中用于获取近期文章的PHP函数使用解析_php技巧

WBOY
WBOYOriginal
2016-05-16 20:00:551075Durchsuche

wp_get_recent_posts 函数在 WordPress 中是一个可以获取近期文章数组的函数,相较于其他的文章获取方式, wp_get_recent_posts 返回的将是一个数组而不是对象,所以在使用中对于一些新手或者是懒人,可能会更方便一些,下面我们就实例讲解一下这个函数。

描述
wp_get_recent_posts
英文解释很短,就不贴了,
中文大概意思是:获取最新文章的函数。
实际上这是一个 get_posts函数的再使用。
描述的再好也木用,下面看使用。

使用/用法

 <&#63;php 
  wp_get_recent_posts( $args ) 
 &#63;>

参数默认值

 <&#63;php $args = array(
//获取的文章数量
  'numberposts' => 10,
//从第几篇开始获取
  'offset' => 0,
//分类的ID,如果不设置则显示全部分类
  'category' => 0,
//排序规则 (注1,下详)
  'orderby' => 'post_date',
//升、降序排列
  'order' => 'DESC',
//包括的文章ID
  'include' => ,
//排除的文章ID
  'exclude' => ,
//自定义字段名称
  'meta_key' => ,
//自定义字段的值,配合上一个参数,来选择显示符合自定义字段数值的文章。
  'meta_value' =>,
//文章类型:文章或页面
  'post_type' => 'post',
//文章状态:草稿、已发布、隐藏文章等....
  'post_status' => 'draft, publish, future, pending, private',
//这个木研究
  'suppress_filters' => true ); 
&#63;>

实例
因为跟 get_posts 的使用方法实在是很相似,
所以就不给什么高深的例子了,简单的给一个官方的例子。

<h2>Recent Posts</h2>
<ul>
<&#63;php
 //获取最新文章
 $recent_posts = wp_get_recent_posts();
 //遍历出每一篇文章。
 foreach( $recent_posts as $recent ){
 echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' .  $recent["post_title"].'</a> </li> ';
 }
&#63;>
</ul>

总结
注意:因为wp_get_recent_posts函数的返回值是一个数组,
setup_postdata 函数理论上只能接受对象类型的变量,
所以按照官方文档的解释是不能使用setup_postdata函数,装载到循环中使用的。
因为用的不多,所以我也就没有去试,有兴趣的同学可以试一试看能否成功。
所以说,如果使用 setup_postdata 函数的话,
wp_get_recent_posts 函数不如 get_posts 函数使用起来方便。

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

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn