Nuts & Bolts WordPress Example: wp_list_pages()

While coding a WordPress plug-in for a client, I needed to retrieve a page’s children.
I ran into the problem, that wp_list_pages() just returns HTML – instead of an object or an array.

There’s some lame solution attempts on the web, but none of them was really sufficient…
I mean, it’s non-sense to get a string from wp_list_pages() and manipulate it afterwards.

So I just developed my very own implementation of function wp_list_pages() …
which gives you full control over the HTML code generation:

function wp_list_children_pages($parent_id){

   global $wpdb;

   $sql = "
      SELECT
         ID,
         post_title,
         post_name
      FROM
         ".$wpdb->prefix."posts
      WHERE
         post_type = 'page'
      AND
         post_status = 'publish'
      AND
         post_parent = ".(int)$parent_id."
      ORDER BY
         menu_order ASC
   ";

   $obj = $wpdb->get_results($sql);
   $html="";

   foreach($obj as $page){

      $id = $page->ID;
      $label = $page->post_title;
      $slug = get_permalink($id);

      $html .= "<li class=\"page_item page-item-".$id."\">".
               "<a href=\"".$slug."\">".$label."</a></li>\n";
   }

   return $html;
}

This blog here deals with a similar topic: “When wp_list_pages() can’t do it…