Click Fraud Protection
PHP related blog, freelancer to hire!

How set active item in primary links menu in Drupal

I wanted to set item to be active from my module. After research i found quite easy way to do it.

I found theme_links() which are preparing menu to be displayed. Copy that into template.php in your theme folder.

My function is quite simple:

function YOURTHEMENAME_links($links, $attributes = array('class' => 'links')) {
global $language;
$output = '';
/**
* Make our item active
*/
if (strpos($_GET['q'],'URLTOMATCH1/') !== false)
{
$org = $_GET['q'];
menu_set_active_item('node/57819'); // nid is taken from primary links
}
if (strpos($_GET['q'],'URLTOMATCH2') !== false)
{
$org = $_GET['q'];
menu_set_active_item('node/57789');
}
if (strpos($_GET['q'],'URLTOMATCH3') !== false)
{
$org = $_GET['q'];
menu_set_active_item('node/57829');
}
// inspiration
if (strpos($_GET['q'],'inspiration') !== false)
{
$org = $_GET['q'];
menu_set_active_item('node/57839');
}
if (count($links) > 0) {
$output = '<ul'. drupal_attributes($attributes) .'>';
$num_links = count($links);
$i = 1;
foreach ($links as $key => $link) {
$class = $key;
// Add first, last and active classes to the list of links to help out themers.
if ($i == 1) {
$class .= ' first';
}
if ($i == $num_links) {
$class .= ' last';
}
if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))
&& (empty($link['language']) || $link['language']->language == $language->language)) {
$class .= ' active';
}
$output .= '<li'. drupal_attributes(array('class' => $class)) .'>';
if (isset($link['href'])) {
// Pass in $link as $options, they share the same keys.
$output .= l($link['title'], $link['href'], $link);
}
else if (!empty($link['title'])) {
// Some links are actually not links, but we wrap these in <span> for adding title and class attributes
if (empty($link['html'])) {
$link['title'] = check_plain($link['title']);
}
$span_attributes = '';
if (isset($link['attributes'])) {
$span_attributes = drupal_attributes($link['attributes']);
}
$output .= '<span'. $span_attributes .'>'. $link['title'] .'</span>';
}
$i++;
$output .= "</li>\n";
}
$output .= '</ul>';
}
// set original value
menu_set_active_item($org);
return $output;
}
3 Comments
  1. This doesn’t seem to be catching my primary or secondary menu links :\

  2. Hi
    Need some help with that? Send code so i can look into it if you want

  3. Hmm… I read blogs on a similar topic, but i never visited your blog. I added it to favorites and i’ll be your constant reader.

Leave a Reply