问题描述

有没有办法在 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 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。