33

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

我希望能够查询一组子页面,然后对它使用THE LOOP函数调用 - 像the_permalink()and之类的东西the_title()

有没有办法做到这一点?我在文档中没有看到任何query_posts()内容。

4

2 回答 2

57

是的,这是可能的。您可以创建一个新的 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以了解这些。

于 2008-10-13T04:47:51.303 回答
22

考虑到这个问题的年龄,我想为任何偶然发现它的人提供一个更新的答案。

我建议避免使用 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

于 2014-02-13T08:19:11.423 回答