2008-10-13 31 views
30

有沒有辦法使用THE LOOPwordpress加載頁面,而不是帖子?使用WordPress的LOOP與頁面而不是帖子?

我希望能夠查詢一組子頁面,然後使用環路上函數調用 - 比如the_permalink()the_title()

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

回答

55

是的,這是可能的。您可以創建一個新的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的來源挖掘瞭解這些。

+0

如果它是當前頁面的子頁面,你可以用`get_the_ID()`如果您以前叫'the_post()`。 – jezmck 2013-10-24 14:44:20

15

考慮到這個問題的年齡,我想爲任何絆倒它的人提供一個更新的答案。

我建議避免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

相關問題