Home >Backend Development >PHP Tutorial >Analysis of PHP function used to obtain recent articles in WordPress development_php skills
The wp_get_recent_posts function in WordPress is a function that can obtain an array of recent articles. Compared with other methods of obtaining articles, wp_get_recent_posts will return an array instead of an object, so for some novices or lazy people in use, It may be more convenient. Let's explain this function with an example.
Description
wp_get_recent_posts
The English explanation is very short, so I won’t post it,
The Chinese probably means: a function to get the latest articles.
In fact, this is a reuse of the get_posts function.
No matter how good the description is, it is useless. Let’s see how to use it.
Usage/Usage
<?php wp_get_recent_posts( $args ) ?>
Parameter default values
<?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 ); ?>
Example
Because the usage method is very similar to get_posts,
So I won’t give any advanced examples, but simply give an official example.
<h2>Recent Posts</h2> <ul> <?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> '; } ?> </ul>
Summary
Note: Because the return value of the wp_get_recent_posts function is an array,
The setup_postdata function can theoretically only accept variables of object type,
Therefore, according to the explanation of the official documentation, you cannot use the setup_postdata function and load it into a loop for use.
Because I don’t use it much, I didn’t try it. Interested students can give it a try to see if they can succeed.
So, if you use the setup_postdata function,
The wp_get_recent_posts function is not as convenient to use as the get_posts function.
Note:
‘author’ —— Sort by author numerical number
‘category’ —— Sort by category numerical number
‘content’ —— Sort by content
‘date’ — Sort by creation date
‘ID’ —— Sort by article number
‘menu_order’ – Sort by menu order. Only pages available.
'mime_type' - Sort by MIME type. Only attachments available.
'modified' - Sort by last modified time.
‘name’ – Sort by stub.
‘parent’ —— Sort by parent ID
‘password’ — Sort by password
‘rand’ —— Arbitrarily sort the results
'status' - Sort by status
‘title’ —— Sort by title
‘type’ —— Sort by type