Unlimited levels and children in a menu

This is a recursive function that allows the user to display an unlimited number of levels and children. It also allows you to limit the number of children that are displayed for particular pages. This is achieved with an array of slug/limit pairs. The function’s options are:

  1. required, The page from where you want to start displaying the menu;
  2. required, The current page;
  3. optional, If true, start with a <UL>
  4. optional, An array of slug/limit pairs where limit is the maximum number of children to display for that particular slug.
<?php

function displayChildren($page, $current, $startmenu = true, $limits = null) {
 
if ($limits != null && array_key_exists($page->slug, $limits)) {
    $arr
= array('order' => 'position ASC, published_on DESC', 'limit' => $limits[$page->slug]);
 
} else
    $arr
= array('order' => 'position ASC, published_on DESC');

 if ($page && count($page->children()) > 0) {
    echo
($startmenu) ? '<ul class="sidemenu">' : '';
   
foreach($page->children($arr) as $menu) :
      echo
'<li>'.$menu->link($menu->title, (in_array($menu->slug, explode('/', $current->url)) ? ' class="current"': null)).'</li>';
      displayChildren
($menu, $current, true, $limits);
    endforeach
;
    echo
($startmenu) ? '</ul>' : '';
 
}
}
?>

Just add the above function to a Snippet or Layout. Then you can use the following code on a page somewhere to produce the actual menu:

<h1>Menu</h1>
<?php
  $page
= $this->find('/');
  echo
'<ul class="sidemenu">';
  echo
'<li>'.$page->link($page->title, (in_array($page->slug, explode('/', $this->url)) ? ' class="current"': null)).'</li>';
  echo displayChildren
($page, $this, false, array('articles' => '3', 'a-sub-page' => '1'));
  echo
'</ul>';
?>