要在 WordPress 取得文章的列表,是使用 get_posts() 這個 function,如果不丟任何參數則會回傳最新的文章。
而完整的參數依官網的文件說明如下:
get_posts( array $args = null );
$args 可帶入的值如下:
- $args
-
(array) (Optional) Arguments to retrieve posts. See WP_Query::parse_query() for all available arguments.
- 'numberposts'
(int) Total number of posts to retrieve. Is an alias of$posts_per_page
in WP_Query. Accepts -1 for all. Default 5. - 'category'
(int|string) Category ID or comma-separated list of IDs (this or any children). Is an alias of$cat
in WP_Query. Default 0. - 'include'
(int[]) An array of post IDs to retrieve, sticky posts will be included. Is an alias of$post__in
in WP_Query. Default empty array. - 'exclude'
(int[]) An array of post IDs not to retrieve. Default empty array. - 'suppress_filters'
(bool) Whether to suppress filters. Default true.
Default value: null
- 'numberposts'
也就是說如果我們要去取得目錄 id 是 1 的文章,而且要取得 3 篇,則把 $args 設定為下:
$args=array( 'numberposts'=> 3, 'category' => 2, ); $posts=get_posts( $args );
接下來就可以用迴圈把資料撈出來:
foreach($posts as $value): echo $value->ID; //文章 ID echo $value->post_title; //文章標題 endforeach;
不清楚有哪些內容可以讀的,可以利用 var_dump($posts); 去取得完整資訊。
回傳的內容會長這樣:
WP_Post Object
(
[ID] =>
[post_author] =>
[post_date] =>
[post_date_gmt] =>
[post_content] =>
[post_title] =>
[post_excerpt] =>
[post_status] =>
[comment_status] =>
[ping_status] =>
[post_password] =>
[post_name] =>
[to_ping] =>
[pinged] =>
[post_modified] =>
[post_modified_gmt] =>
[post_content_filtered] =>
[post_parent] =>
[guid] =>
[menu_order] =>
[post_type] =>
[post_mime_type] =>
[comment_count] =>
[filter] =>
)
撈出來的文章是沒有文章縮圖的,如果有需要顯示縮圖,則可以利用 get_the_post_thumbnail() 這個 function 去取得。
更多內容可以參考官方文件說明