更新日期:2014-08-16
get_posts 函數用於抓取多篇指定、某分類或隨機的文章。
語法:
$args = array( 'posts_per_page' => 5, 'offset' => 0, 'category' => '', 'orderby' => 'post_date', 'order' => 'DESC', 'include' => '', 'exclude' => '', 'meta_key' => '', 'meta_value' => '', 'post_type' => 'post', 'post_mime_type' => '', 'post_parent' => '', 'post_status' => 'publish', 'suppress_filters' => true ); $posts_array = get_posts( $args );
說明一下幾個常用的項目,
posts_per_page 是每頁顯示多少篇文章,如果換成 numberposts 就是取出幾篇文章就好。
offset 是從第幾篇開始顯示,0表示第一篇。
orderby 是依照哪個條件(欄位)排序。
include 是指定哪些文章id。
exclude 是排除哪些文章id。
post_type 是取哪些類型,post 就是文章。
post_status 是文章發佈狀態,publish 為已發佈。
這樣子的 $posts_array 返回值是 objects,做迴圈就可以一一將標題、內容、發文時間等等顯示出來了。
舉例用法:
$args = array( 'numberposts' => 5, // 取5篇 'category' => 1, // 分類編號為1 'orderby' => 'post_date', // 依照發文時間排序 'order' => 'DESC', // 由新到舊排序 'post_type' => 'post', // 取類型是文章 'post_status' => 'publish' // 已經發表的文章 ); $postslist = get_posts( $args ); foreach ( $postslist as $post ){ setup_postdata( $post ); // 利用 setup_postdata 把我們的查詢放入 $post echo '<div>'; if ( has_post_thumbnail() ) the_post_thumbnail(); echo '<a href="' . get_permalink() . '">' . get_the_title() . '</a></div>'; } wp_reset_postdata(); // 重置 setup_postdata()