34

Is there a way to use THE LOOP in Wordpress to load pages instead of posts?

I would like to be able to query a set of child pages, and then use THE LOOP function calls on it - things like the_permalink() and the_title().

Is there a way to do this? I didn't see anything in query_posts() documentation.

2 Answers 2

57

Yes, that's possible. You can create a new WP_Query object. Do something like this:

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_parent and more important post_type are not listed there. I dug through the sources of ./wp-include/query.php to find out about these.

Sign up to request clarification or add additional context in comments.

1 Comment

If it's child pages of the current page you can use get_the_ID() if you've previously called the_post().
22

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:

$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.

Further reading: http://codex.wordpress.org/Class_Reference/WP_Query

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.