Here’s a quick guide on how to generate a list of sub pages in a WordPress template.
Firstly create a page which will act as the ‘Parent’ item and then create some other pages and assign the Parent page to each in the ‘Page Attributes’ box. Then onto our template file in this case i named the page ‘example’ so the template file will be called ‘page-example.php‘. Create the new file substituting you page name for ‘example’ and add in the code below. I have split it into three chunks to explain it, or click here for the full loop script.
So this little bit sets up the arguments for the <em>WP_Query()</em> function. In this case I’ve passing the page id we got earlier in as the parent page id using the thisID variable which means that only sub pages of this page will be returned. Then I define the post_type as page, do not forget this as WP_Query() defaults to ‘post’ which will return no pages or sub pages. The posts_per_page parameter will return all the sub pages when its set to minus one, or you can place your own integer in there, or alternatively leave it out and the pages will be shown as per the settings in the WordPress dashboard.
<?php $args = array( 'post_parent' => $thisID, 'post_type' => 'page', 'posts_per_page' => '-1', 'order' => 'asc', );
Next up we run the new loop.
<?php /* The loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <div <?php post_class( 'example' ); ?><role="main"> <div class="entry">
We begin the new loop by setting up a new instance of WP_Query() using our custom arguments, and setting up the post data if there are any posts with the while statement. Then we created a link to each subpage, using the_permalink(), get_the_title() and the_title(), then we close off the second loop and the surrounding div elements. Voila a list of a pages sub pages each linking to the sub page.
$query = new WP_Query($args); while( $query->have_posts() ) { $query->the_post(); ?> <a title="<?php the_title_attribute(); ?>" href="<?php the_permalink(); ?>"><Link to post</a> <h4 class="sub-page-title"><?php the_title(); ?></h4> <?php } ?> </div> </div>
Comment if you have any ideas on how I could do it better!
Here’s the whole thing:
<?php $args = array( 'post_parent' => $thisID, 'post_type' => 'page', 'posts_per_page' => '-1', 'order' => 'asc', ); $query = new WP_Query($args); while( $query->;have_posts() ) { $query->the_post(); ?> <a title="<?php the_title_attribute(); ?>" href="<?php the_permalink(); ?>"><Link to post</a> <h4 class="sub-page-title"><?php the_title(); ?></h4> <?php } ?></div> </div> <?php /* The loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <div <?php post_class( 'example' ); ?><role="main"> <div class="entry">
lol