将Wordpress LOOP用于页面而不是帖子


Using Wordpress LOOP with pages instead of posts?

有没有办法在Wordpress中使用THE LOOP加载页面而不是帖子?

我希望能够查询一组子页面,然后对其使用THE 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