[WP] 利用 get_posts 得到 Previous Posts
Published by hsuyo 5:03 PM, May 31st, 2006 in WordPress Tags: wordpress.左下角的 Previous Posts,是用 get_posts 得到的小型文章 loop。
1. 基本的用法:
<?php
$posts = get_posts('numberposts=5&offset=3&category=1');
foreach($posts as $post) :
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
/* numberposts= 指定文章數量; offset= 顯示第 n 篇後的文章; category= 指定分類 (0=不指定) */
則會顯示分類 ID=1 之中,去掉最新 3 篇文章之後的 5 篇文章標題連結;
若要加入文章的日期跟留言,則在 <?php the_title(); ?> 與 </a> 之間加入:
<?php the_time('F jS, Y'); ?> <?php comments_number('| No comments yet','| Comments (1)','| Comments (%)', 'number'); ?>
/* 時間參數與留言數字格式可以自訂 */
2. 要注意的是,如果 get_posts 放在 The Loop 之前 (ex: 想把舊文章顯示在版面上方),則會連帶影響到首頁文章的顯示。以上面為例,分類 ID=1 的最新 3 篇文章也不會出現在首頁。這時,要使用 query_posts 將 The Loop 重置。
先在 Theme 資料夾中的 index.php 找到 The Loop 的開頭:
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
在 The Loop 之前,加入
<?php query_posts($query_string); ?>
這樣一來,才能讓首頁的文章正常顯示。
如果 get_posts 是出現在 The Loop 之後 (像我目前的配置),則不會影響,也不用 query_posts。
3. 當然,嫌麻煩的話,也可以使用 cypher Previous Posts 或是 Show Range Post 的 plugin 達到類似的簡單效果。
4. 問題待解: 如何把不想顯示的分類文章 (ex: Asides 的文章) 排除在外呢?
你曾經發過文解釋過的-Front Page Categories-這個外掛。
我自己架的幾個WP都有用這個,對於學校用的網頁這還蠻好用的
我誤會了~如果你是指小型迴圈裡的,目前只有暴力法-硬指定顯示的分類。至少目前我的作法是這樣,沒看到好用的外掛,查WP官網也沒什麼發現~倒是有在想修改上述那個外掛不知道可不可行…
恩..我有想過硬指定顯示的分類
但是 get_posts 內的參數不會下 @@
如果我想顯示 id 1 和 id 3 的分類文章
是 category=1, 3 嗎? (還是 category=1&3 ?)
我試過但好像無法正確顯示