background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount

Creating a menu item with a dynamic title

Eric.London's picture

In this code snippet I'll explain how to create a menu item that has a dynamic title.

<?php
// define hook_menu to create menu item
function MYMODULE_menu() {
 
$items = array();
   
 
$items['MY/PAGE/URL/%'] = array(
   
'page callback' => 'MY_PAGE_CALLBACK_FUNCTION',
   
'title callback' => 'MY_PAGE_CALLBACK_TITLE_FUNCTION',
   
'title arguments' => array(3),
   
'type' => MENU_CALLBACK,
  );

  return
$items;
}

// define title callback function
function MY_PAGE_CALLBACK_TITLE_FUNCTION($arg) {
  return
"My dynamic title: " . $arg;
}
?>

In the above example, if you browsed to the URL: MY/PAGE/URL/blah-blah-blah, you'd have a page title of: My dynamic title blah-blah-blah. In a more applicable example, you might need to pass the node id to the callback function and then return: $node->title;

Check out the documentation on wildcard loader arguments for more advanced options.

Thanks for this

Really came in handy to a Drupal noob such as I.
Thanks!

Thanks, Dynamic menu Really works

Thnks, I m wondering to get this answer from last three four days.

MY_PAGE_CALLBACK_TITLE_FUNCTION

I tried the technique, but it does not work as expected.
Page title comes out blank.

<?php
   
/* list Author */
 
$items['list/author/%'] = array(
   
//'title' => t('list for author'),
   
'page callback' => 'list_by_author',
   
'title callback' => 'MY_PAGE_CALLBACK_TITLE_FUNCTION',
   
'title arguments' => array(2),
   
'access arguments' => array('access content'),   
   
'type' => MENU_CALLBACK,
   
'file' => 'list.pages.inc',
  );
 
 
// define title callback function
function MY_PAGE_CALLBACK_TITLE_FUNCTION($arg) {
 
//echo $arg
  //die();   -- I am capturing the arg
return "List by Author: " . $arg;
}
?>

Thanks!

Was looking for this exact example! Thanks for the info.

-glitch

HI

thnks for the info