Hello. I am trying to figure out how add classes to menu items via a custom module. The menu_attributes.api.php file seems to only cover adding new attributes that can be set for menu items.

Thanks!

Sean

Comments

reign85’s picture

Up. I need it too.

It will be nice if we can use it programaticaly liek this:

<?php
function agency_menu(){
$items['itineraire/%'] = array(
       
'title' => 'title',
       
'page callback' => '_calculate_iti',
       
'page arguments' => array(1),
       
'access arguments' => array('access content'),
       
'type' => MENU_CALLBACK,
attributes => array('target' => '_blank')
    );
}
?>

But maybe another way to do this exist? without using the UI

dobe’s picture

You can, I just tried and tested this. Since the attributes are stored in the menu_links.options column of the database. You can do this with your example above.

<?php
function agency_menu(){
$items['itineraire/%'] = array(
       
'title' => 'title',
       
'page callback' => '_calculate_iti',
       
'page arguments' => array(1),
       
'access arguments' => array('access content'),
       
'type' => MENU_CALLBACK,
       
'options' => array('attributes' => array('target' => '_blank', 'class' => array('itineraire'))),
    );
}
?>

Let me know if this doesn't work for you. As it has worked for me.

ADrupalUser’s picture

Issue summary:View changes

Is it possible to set the attributes dynamically? I'd like to colorize a menu option (by adding a css class) only under certain conditions.

dobe’s picture

Probably best way to do this is via javascript. The context module may be able to do this as well for you.

-Jesse

ADrupalUser’s picture

Thanks. In my case, I was able to use Menu CSS Names instead, as the menu text also changes when it needs to be colorized.

geerlingguy’s picture

Also, if you just want to programmatically update an existing link (but not modify it in hook_menu or _alter...):

<?php
$mlid
= [menu-link-id-here];
if (
$menu_link = menu_link_load($mlid)) {
 
$menu_link['options'] = array('attributes' => array('class' => array('classname')));
 
menu_link_save($menu_link);
}
?>
diqidoq’s picture

Follow up #2524398: Support for UI based custom attributes
(related issue added)

diqidoq’s picture

Another suggestion: use https://www.drupal.org/project/menu_fields. This maybe renders this feature/support request obsolete?

joelpittet’s picture

Status:Active» Fixed

Answered in #6 and more solutions in #7 and #8