HowTo: Add / Remove a menu_local_task for specific node types

While writing a custom module with it's own content type, I needed to add a menu_local_task to node/x/edit path AND for it to only show up when editing the custom content type.

Adding a menu local task is easy, but hiding it from other content types proved fruitless. And, it seems many others had similar needs and problems.

Using hook_menu_alter or hook_menu_link_alter was not cutting it. I even pulled out my trusty PDD (Drupal 6) to see what it had to say. Reading about the x_to_arg() seemed would help, but no go.

After banging my head, I realized my problem could be easily solved through the menu 'access callback'. So, I had another Drupal gotcha moment; more than an hour spent on discovering a solution (the Drupal way) that only took 6 lines of code to fix.

Ok, here is the code to add a menu_local_task for a specific content type:


<?php

/**
* implementation of hook_menu()
*/
function mymodule_menu() {

$items = array();

$items['node/%node/edit/attributes'] = array(
'title' => 'Attributes',
'page callback' => 'drupal_get_form',
'page arguments' => array('mymodule_attributes_form', 1),
'access callback' => 'mymodule_attributes_access',
'access arguments' => array(1),
'weight' => 10,
'type' => MENU_LOCAL_TASK,
);

return $items;
}

/**
* Access callback for node/%node/edit/attributes.
*/
function mymodule_attributes_access($node) {
if ($node->type != 'mymodule') {
return FALSE;
}
return TRUE; // TRUE or you can user user_access() permissions as well
}

?>

Enjoy!

Comments

Its always difficult to add or remove a menu especially while writing custom module. But I dont think it is a problem now, as I have read this post.