List pages in wordpress into a PHP Array

List pages in wordpress into a PHP Array

Update: Thanks to Joost in the comments for suggesting the use of get_pages() to accomplish the same thing as what I posted below. He posted the example:

$pages = get_pages(‘child_of’ => [[THE PARENT ID]], ’sort_order’ => ‘ASC’); foreach ($pages as $page) { // Do your thang }

This seems much better than what I had previously used, but for reference, my old post is below:

I spent some time figuring out how to get the wordpress wp_list_pages function to return the results as a PHP array of URLs and page names. There wasn't an obvious way to do this and searching google did not yield anything particularly useful. The wp_list_pages function has an "echo" parameter which when set to 0 returns a list of links as a string. That won't help much if you want it as an array with links and page names.

I ended up writing a short script that will query wordpress for the name and URL of all of the subpages of a specified page. This could be used to make a function that formatted a list of pages a particular way (like making the list wrap into two or more columns). Its nothing fancy, but perhaps it can help other wordpressers who are looking for something similar.

<?php $querystr = "SELECT $wpdb->posts.\* FROM $wpdb->posts WHERE $wpdb->posts.post\_status = 'publish' AND $wpdb->posts.post\_type = 'page' AND $wpdb->posts.post\_parent = \[\[Parent Page ID\]\] ORDER BY $wpdb->posts.post\_title ASC"; $pageposts = $wpdb->get\_results($querystr, OBJECT); if ($pageposts): foreach ($pageposts as $post): setup\_postdata($post); // Add your own logic or formatting here ?> <a href="<?php the\_permalink() ?>" title="Permanent Link to <?php the\_title(); ?>"><?php the\_title(); ?></a> <?php endforeach; else : echo 'Not Found'; endif; ?>

Where [[Parent Page ID]] is the id number of the parent page you would like to get children from. If you want all pages included, don't include this parameter.