WordPress获取最新文章函数:wp_get_recent_posts
WordPress函数wp_get_recent_posts用于获取最新文章,包括文章的标题、别名、状态、发表时间、修改时间、内容等信息。
wp_get_recent_posts( array $args, string $output )
函数参数
$args
数组
wp_get_recent_posts()函数$args参数默认的值如下:
$args = array( 'numberposts' => 10, 'offset' => 0, 'category' => 0, 'orderby' => 'post_date', 'order' => 'DESC', 'include' => '', 'exclude' => '', 'meta_key' => '', 'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private', 'suppress_filters' => true );
wp_get_recent_posts()函数$args参数可用的值如下:
numberposts
整数,默认值:10
指定要返回的文章数量
offset
整数,默认为空
偏移数,例如设置为2,则从最新的第3篇文章开始返回数据。
category
整数,默认值:0
分类的ID,指定需要返回哪个分类的文章。
orderby
字符串值,默认值:post_date
按照哪个字段来排序,默认按照文章的发表时间排序。
order
字符串值,默认值:DESC
排序的方式
include
整数、数组或字符串值,默认为空
需要包含的文章ID,只有指定的这些文章才会被返回。
exclude
整数、数组或字符串值,默认为空
需要排除的文章ID,指定的这些文章不会被返回。
meta_key
字符串值,默认为空
自定义字段的名称,用于筛选文章
meta_value
字符串值,默认为空
自定义字段的值,用于筛选文章
post_type
字符串值,默认值:post
文章类型,默认为返回post类型的文章
post_status
字符串值,默认值:draft, publish, future, pending, private
文章的状态,可在以上值中只选择一种,例如设置为publish,则只返回公开的文章。
suppress_filters
布尔值,默认值:true
是否使用过滤器
wp_get_recent_posts()函数还有第二个参数:
$output
字符串值,默认值:ARRAY_A
- ARRAY_A:返回数组结构的数据;
- OBJECT:返回对象;
函数返回值
Array ( [0] => Array ( [ID] => 2436 [post_author] => 1 [post_date] => 2019-03-22 08:03:33 [post_date_gmt] => 2019-03-22 0:03:33 [post_content] => [post_title] => 文章标题 [post_excerpt] => [post_status] => publish [comment_status] => open [ping_status] => closed [post_password] => [post_name] => 文章别名 [to_ping] => [pinged] => [post_modified] => 2019-03-22 10:13:46 [post_modified_gmt] => 2019-03-22 02:13:46 [post_content_filtered] => [post_parent] => 0 [guid] => https://www.tiezhushuo.com/?p=2436 [menu_order] => 0 [post_type] => post [post_mime_type] => [comment_count] => 0 [filter] => raw ), [1] => Array ( ...... ) ...... )
函数使用示例
以下代码会输出10篇最新文章列表,注意在输出结果之后,使用了wp_reset_query()函数来重置循环,避免下一个查询出现错误。
<h2>最新文章</h2> <ul> <?php $recent_posts = wp_get_recent_posts(); foreach( $recent_posts as $recent ){ echo '<li><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"] . '</a></li>'; } wp_reset_query(); ?> </ul>
扩展阅读
wp_get_recent_posts()函数位于:wp-includes/post.php
相关函数:
- wp_parse_args()
- get_posts()
-
如何创建WordPress古腾堡编辑器的区块(PHP+原生JS) 2024-01-10 01:01:06
-
搭建一个WordPress网站需要多少成本 2023-11-06 00:09:51
-
Symlink介绍(附:如何使用Symlink进行WordPress开发) 2023-11-05 23:38:32
-
让WordPress实现数据库同步的插件:HyperDB 2023-10-24 23:40:49
-
allegro电商平台值得做吗(附:2023年Allegro注册流程指南) 2023-10-08 21:53:39
-
印度跨境电商平台有哪些(附:印度跨境电商做什么产品好) 2023-10-08 21:34:23
-
跨境电商必看的几大海外二手电商平台 2023-10-08 18:04:42
-
WordPress同城互联网产品解决方案:UBASE 2023-10-03 16:40:39
-
WordPress网站的安全插件:wordfence 2023-09-14 09:25:18
-
WordPress 6.3 支持在手动更新插件和主题失败后回滚旧版本 2023-08-28 16:58:45