How to add class “last” to last menu item (li) in Joomla 1.5 (mod_mainmenu)

Create new file default.php and place it in /[your_template]/html/mod_mainmenu/, add next content to it:

<?php

// no direct access
defined('_JEXEC') or die('Restricted access');

if ( ! defined('modMainMenuXMLCallbackDefined') )
{

//class to add class "last" to last li
function addLastClass($result) {
$result = preg_replace("/(.*)<\/li><li class=\"item(\d*)\">(.*)<\/li><\/ul>(.*).*/is", '$1</li><li>$3</li></ul>$4', $result);

return $result;
}

function modMainMenuXMLCallback(&$node, $args)
{
$user    = &JFactory::getUser();
$menu    = &JSite::getMenu();
$active    = $menu->getActive();
$path    = isset($active) ? array_reverse($active->tree) : null;

if (($args['end']) && ($node->attributes('level') >= $args['end']))
{
$children = $node->children();
foreach ($node->children() as $child)
{
if ($child->name() == 'ul') {
$node->removeChild($child);
}
}
}

if ($node->name() == 'ul') {
foreach ($node->children() as $child)
{
if ($child->attributes('access') > $user->get('aid', 0)) {
$node->removeChild($child);
}
}
}

if (($node->name() == 'li') && isset($node->ul)) {
$node->addAttribute('class', 'parent');
}

if (isset($path) && (in_array($node->attributes('id'), $path) || in_array($node->attributes('rel'), $path)))
{
if ($node->attributes('class')) {
$node->addAttribute('class', $node->attributes('class').' active');
} else {
$node->addAttribute('class', 'active');
}
}
else
{
if (isset($args['children']) && !$args['children'])
{
$children = $node->children();
foreach ($node->children() as $child)
{
if ($child->name() == 'ul') {
$node->removeChild($child);
}
}
}
}

if (($node->name() == 'li') && ($id = $node->attributes('id'))) {
if ($node->attributes('class')) {
$node->addAttribute('class', $node->attributes('class').' item'.$id);
} else {
$node->addAttribute('class', 'item'.$id);
}
}

if (isset($path) && $node->attributes('id') == $path[0]) {
$node->addAttribute('id', 'current');
} else {
$node->removeAttribute('id');
}
$node->removeAttribute('rel');
$node->removeAttribute('level');
$node->removeAttribute('access');
}
define('modMainMenuXMLCallbackDefined', true);
}
//get menu code
ob_start();

modMainMenuHelper::render($params, 'modMainMenuXMLCallback');

//add class "last" to last li
$menu_html = ob_get_contents();
ob_end_clean();

echo addLastClass($menu_html);

2 Responses to “How to add class “last” to last menu item (li) in Joomla 1.5 (mod_mainmenu)”

  1. arun kumar says:

    Hi Mr.fragov ,

    Thank you so much for the code.
    It worked for me great. but i had changed this line of code as follows, as by default there is no class for the lat li and i had added up the class.

    $result = preg_replace(“/(.*)(.*)(.*).*/is”, ‘$1$2$3′, $result);

    once again thank you.

Leave a Reply