Add number of items as a class to menus I would like to add a class to menu that shows how many items are in that particular level.  I.E.

&lt;ul class="menu count-5"&gt;
  &lt;li&gt;1&lt;/li&gt;
  &lt;li&gt;2&lt;/li&gt;
  &lt;li&gt;3&lt;/li&gt;
  &lt;li&gt;4&lt;/li&gt;
  &lt;li&gt;5&lt;/li&gt;
&lt;/ul&gt;


What's the best way to do this?

I've looked at theme_menu_tree but the tree is already rendered html by that point so there is no easy way to count the number of items.
It really feels like there should be a better way to do this (but I can't find one at the moment, theme_menu_link() isn't context-aware of its parent menu); however this will work:

function MYMODULE_menu_tree(&amp;$variables) {
  // Load the current HTML into a DOMDocument to count the links
  $doc = new DOMDocument;
  $doc-&gt;loadHTML('&lt;ul class="identifiable-string"&gt;' . $variables['tree'] . '&lt;/ul&gt;');

  // XPath query to find only top-level &lt;li&gt;s
  $xpath = new DOMXPath($doc);
  $lis = $xpath-&gt;query('//ul[@class="identifiable-string"]/li');

  // Get the count based on the number of elements returned
  $count = 0;
  if ($lis) {
    foreach ($lis as $li) {
      $count++;
    }
  }

  return '&lt;ul class="menu count-' . $count . '"&gt;' . $variables['tree'] . '&lt;/ul&gt;';
}


It seems like a huge amount of effort (not to mention processor power) for not much reward, but if you're struggling then this method will definitely work.