在 WordPress 中讀取文章列表都是通過 loop 形式獲取的,」Loop(循環)」 是一個指明 WordPress 主要程序過程的術語。你在你的模板 template files 中應用循環來把你的文章表現給讀者。特別的在我們製作 WordPress 主題首頁過程中,經常需要遍歷數據,讀取最新的文章列表,接下來讓我們具體來看下 WordPress Loop(循環) 的使用,以下我們以主題首頁模板 index.php 為例:

  < ?php

  get_header();

  //Loop 開始

  if (have_posts()) :

  while (have_posts()) :

  the_post();

  the_content();

  endwhile;

  endif;

  //Loop 結束

  get_sidebar();

  get_footer();

  ? >

  以上實例僅展示了每篇文章的內容,使用中視具體情況去調整循環

  Loop 解析

  在以上 index.php 實例中,可以看到 Loop 如何開始的代碼為:

  < ?php if (have_posts()) : ? >

  < ?php while (have_posts()) : the_post(); ? >

  首先, 通過 have_posts() 方法來檢查是否有文章。

  如果有文章, PHP while 循環開始. while 循環會一直執行一直到其括號裏的條件為真。所以直到 have_posts() 返回真,while 循環就不會停止 (have_posts() 方法單純的檢查下一篇文章能否找到。如果找到了,if 判斷返回真,while 循環就再次執行; 如果沒有下一篇文章,if 判斷返回假,跳出循環) 。

  the_post() 方法可以使得讀取當前文章數據的函數生效,如果沒有 the_post(), 大多數模板標籤是無法使用的。

  獲取文章的標題、日期及作者

  下面的模板標籤可以輸出當前文章標題,時間和作者。

  < h2 id="post-" >

  < a href="" rel="bookmark" title="Permanent Link to " >

  < ?php the_title(); ? > < !--文章標題-->

  < /a >

  < /h2 >

  < small >

  < ?php the_time('F jS, Y') ? > < !--日期-- >

  by < ?php the_author() ? > < !--作者-- >

  < /small >

  獲取文章內容

  文章內容可以通過循環體內的 the_content() 函數直接輸出獲取。 get_the_content() 為返回文章內容,你可以對讀取的文章內容進行過濾截取。

  < div >

  < ?php the_content('閲讀全文 »'); ? >

  < /div >