How to use hook_menu function

Public

Here is code I use over and over for custom modules.

Get raw version
php
  1. function MYMODULE_menu() {
  2. $items = array();
  3. $items['path/to/the/%node'] = array( // this automatically runs node_load
  4. 'title' => 'My cool title', // Optional. You don't need to use this.
  5. 'description' => 'This is the description', // Does not really do anything...
  6. 'page callback' => 'my_custom_function', // Function name to be called when this rought is used
  7. 'access arguments' => array('access content'), // Optional "permissions" used
  8. 'access callback' => 'user_is_logged_in', // Optional function for permissions. For granting to everybody simply use 'access callback' => TRUE,
  9. 'page arguments' => array(3), // The page arguments to be used. This returns arg(0) to the page callback function
  10. );
  11. $items['path/is/statuc'] = array( // this path has no arguments.
  12. 'title' => 'My cool title', // Optional. You don't need to use this.
  13. 'description' => 'This is the description', // Does not really do anything...
  14. 'page callback' => 'my_cool_function', // Function name to be called when this rought is used
  15. 'access arguments' => array('access content'), // Optional "permissions" used
  16. 'access callback' => 'user_is_logged_in', // Optional function for permissions. For granting to everybody simply use 'access callback' => TRUE,
  17. );
  18. $items['two/vars/%/%node'] = array(
  19. 'page callback' => 'mix_two_args', // Function name to be called when this rought is used
  20. 'access callback' => 'user_is_logged_in', // Optional function for permissions. For granting to everybody simply use 'access callback' => TRUE,
  21. 'page arguments' => array(2,3), // just like if you used arg(2) and arg(3).
  22. );
  23.  
  24. return $items;
  25. }
  26.  
  27. function my_custom_function($node) {
  28. // $node is already loaded.
  29. // Do what you want here and create a return $output;
  30. $output = $node->title;
  31. return $output;
  32. }
  33.  
  34. function my_cool_function() { // no function argument because 'page arguments' was not used in the hook_menu
  35. // Do what you want here and create a return $output;
  36. $output = 'The date is ' . date('M j, Y');
  37. return $output;
  38. }
  39.  
  40. function mix_two_args($user_uid, $node) {
  41. // if you use % in the path than it simply drops in the var that was passed. This can be a string.
  42. // If you use %node in the path than it loads the node and the var must be an integer.
  43. $user = user_load($user_uid);
  44. $output = 'The user is ' . $user->name . ' and the node is ' . $node->title;
  45. return $output;
  46. }