Letting primary links be active / highlighted when browsing sub paths by overriding theme_links() function in Drupal
I wanted to highlight the primary links when browsing the secondary links (or sub links of the primary links). After some googling I understood that I had to override the theme_link() function. The overriding basically looks if the first slash text is in the in the link url currently active in the loop. All this is dependent on URL aliases being activated. It then proceeds to add the active class to the anchor.
After I messed with the theme_link() function I placed it in the template.php page which now looks likes this
<?php
function myThemeName_links($links, $attributes = array('class' => 'links')) {
$output = '';
if (count($links) > 0) {
$output = '<ul'. drupal_attributes($attributes) .'>';
$num_links = count($links);
$i = 1;
foreach ($links as $key => $link) {
$class = '';
// Automatically add a class to each link and also to each LI
if (isset($link['attributes']) && isset($link['attributes']['class'])) {
$link['attributes']['class'] .= ' ' . $key;
$class = $key;
}
else {
$link['attributes']['class'] = $key;
$class = $key;
}
####### Added Part ############
# Check if current link item is the one currently active
# add active class.
# Check if this is primary links
if ( $attributes['id'] == 'navlist' ) {
$crrntPathArray = array();
$crrntPathArray = explode('/',drupal_get_path_alias($_GET['q']));
# Check if parts of current path is in link path.
if ( stristr( drupal_get_path_alias($link['href']), $crrntPathArray[0] ) )
{ $link['attributes']['class'] .= ' active'; }
}
###########################
// Add first and last classes to the list of links to help out themers.
$extra_class = '';
if ($i == 1) {
$extra_class .= 'first ';
}
if ($i == $num_links) {
$extra_class .= 'last ';
}
$output .= '<li class="'. $extra_class . $class .'">';
// Is the title HTML?
$html = isset($link['html']) && $link['html'];
// Initialize fragment and query variables.
$link['query'] = isset($link['query']) ? $link['query'] : NULL;
$link['fragment'] = isset($link['fragment']) ? $link['fragment'] : NULL;
if (isset($link['href'])) {
$output .= l($link['title'], $link['href'], $link['attributes'], $link['query'], $link['fragment'], FALSE, $html);
}
else if ($link['title']) {
//Some links are actually not links, but we wrap these in <span> for adding title and class attributes
if (!$html) {
$link['title'] = check_plain($link['title']);
}
$output .= '<span'. drupal_attributes($link['attributes']) .'>'. $link['title'] .'</span>';
}
$i++;
$output .= "</li>\n";
}
$output .= '</ul>';
}
return $output;
}
?>