Site icon Hip-Hop Website Design and Development

html sitemap via recursive function

I’m trying to render my page structure as an ordered list (<ol>) showing the hierarchy using nested ordered lists. So it should look something like

<ol>
  <li>
    About
    <ol>
      <li>
        Leadership
        <ol>
          <li>CEO</li>
          <li>COO</li>
        </ol>
      </li>
    </ol>
  </li>
  <li>Services</li>
  <li>Products</li>
</ol>

or

  1. About
    1. Leadership
      1. CEO
      2. COO
  2. Services
  3. Products

I created a function to get 1 level of pages which I call recursively for any pages with child pages.

function aiv_get_sibling_pages($cur_page = null) {
    $front_page_id = get_option('page_on_front');
    $next_page = $cur_page ? $cur_page : get_post($front_page_id);

    $out = '';

    $pages_args = array(
        'exclude' => '', /* ID of pages to be excluded, separated by comma */
        'post_type' => 'page',
        'post_status' => 'publish',
        'parent' => $next_page -> post_parent
    );
    $pages = get_pages($pages_args);

    $out .= '<ol>';
    foreach($pages as $page) {
        $next_page = $page;

        $out .=  '<li>';
        $out .= $page -> post_title;
        $child_pages = get_pages('child_of=' . $page->ID);
        if(count($child_pages) > 0) {
            $out .= aiv_get_sibling_pages($next_page);
        }
        $out .= '</li>';   
    }
    $out .= '</ol>';

    return $out;
}

Everything works as expected until the recursive part: aiv_get_sibling_pages($next_page);

This produces the error:

PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 4096 bytes) in /home/anupadmin/example.com/wp-includes/post.php on line 5781

I’m not entirely sure what that means, but I’m guessing if I’m running out of memory that I’m doing something inefficiently. Can anyone point me towards a better way to do this or shed some light on why I"m getting the error?