問題描述

有沒有辦法在 Wordpress 中使用 LOOP 來載入頁面而不是帖子?

我想要查詢一組子頁面,然後使用它的 LOOP 函式呼叫 – 如 the_permalink()the_title()

有沒有辦法做到這一點?在 query_posts()檔案中沒有看到任何內容。

最佳解決方法

是的,這是可能的。您可以建立一個新的 WP_Query 物件。做這樣的事情:

query_posts(array('showposts' => <number_of_pages_to_show>, 'post_parent' => <ID of the parent page>, 'post_type' => 'page'));

while (have_posts()) { the_post();
    /* Do whatever you want to do for every page... */
}

wp_reset_query();  // Restore global post data

另外還有很多其他可以用於 query_posts 的引數。有些,但不幸的是不是全部,列在這裡:http://codex.wordpress.org/Template_Tags/query_posts 。至少 post_parent 和更重要的 post_type 不在那裡列出。我挖掘了./wp-include/query.php 的來源,以瞭解這些。

次佳解決方法

鑑於這個問題的年齡,我想為任何絆腳石的人提供一個更新的答案。

我建議避免 query_posts 。這是我喜歡的替代方案:

$child_pages = new WP_Query( array(
    'post_type'      => 'page', // set the post type to page
    'posts_per_page' => 10, // number of posts (pages) to show
    'post_parent'    => <ID of the parent page>, // enter the post ID of the parent page
    'no_found_rows'  => true, // no pagination necessary so improve efficiency of loop
) );

if ( $child_pages->have_posts() ) : while ( $child_pages->have_posts() ) : $child_pages->the_post();
    // Do whatever you want to do for every page. the_title(), the_permalink(), etc...
endwhile; endif;

wp_reset_postdata();

另一個替代方案是使用 pre_get_posts 過濾器,但這隻適用於這種情況,如果您需要修改主迴圈。上述示例在用作輔助迴路時更好。

進一步閱讀:http://codex.wordpress.org/Class_Reference/WP_Query

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。