php 将 Wordpress LOOP 用于页面而不是帖子?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/196505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Wordpress LOOP with pages instead of posts?
提问by ashchristopher
Is there a way to use THE LOOPin Wordpressto load pages instead of posts?
有没有办法在Wordpress 中使用THE LOOP来加载页面而不是帖子?
I would like to be able to query a set of child pages, and then use THE LOOPfunction calls on it - things like the_permalink()and the_title().
我希望能够查询一组子页面,然后对其使用THE LOOP函数调用 - 诸如the_permalink()和 之类的东西the_title()。
Is there a way to do this? I didn't see anything in query_posts()documentation.
有没有办法做到这一点?我在query_posts()文档中没有看到任何内容。
回答by Simon Lehmann
Yes, that's possible. You can create a new WP_Query object. Do something like this:
是的,这是可能的。您可以创建一个新的 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
Addition: There are a lot of other parameters that can be used with query_posts. Some, but unfortunately not all, are listed here: http://codex.wordpress.org/Template_Tags/query_posts. At least post_parentand more important post_typeare not listed there. I dug through the sources of ./wp-include/query.phpto find out about these.
补充:还有很多其他参数可以与 query_posts 一起使用。这里列出了一些,但不幸的是不是全部:http: //codex.wordpress.org/Template_Tags/query_posts。至少post_parent,更重要的post_type是没有列出。我挖掘了 的来源./wp-include/query.php以了解这些。
回答by Nathan Dawson
Given the age of this question I wanted to provide an updated answer for anyone who stumbles upon it.
鉴于这个问题的年龄,我想为任何偶然发现它的人提供更新的答案。
I would suggest avoiding query_posts. Here's the alternative I prefer:
我建议避免 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();
Another alternative would be to use the pre_get_posts filter however this only applies in this case if you need to modify the primary loop. The above example is better when used as a secondary loop.
另一种选择是使用 pre_get_posts 过滤器,但这仅适用于需要修改主循环的情况。当用作辅助循环时,上面的示例更好。
Further reading: http://codex.wordpress.org/Class_Reference/WP_Query

