Add your own custom user permissions in Drupal 7

Add your own custom user permissions in Drupal 7

Say you created a module that has a page that only certain user roles should be able to access. If you’re not using Panels/Page Manager (which can limit per user role) and you’re using your own hook_menu item, you’ll need to come up with your own permission that will show up on /admin/people/permissions. Its good to create your custom permissions since it allows you to easily modify permissions without affected other pieces of the site.

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();
  $items['do-fantastic'] = array(
    'title' => 'Do Something Fantastic',
    'page callback' => 'mymodule_do_fantastic',
    'access arguments' => array('do something fantastic'), // custom permission we created
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implements hook_permission().
 */
function mymodule_permission() {
  return array(
    'do something fantastic' => array(
      'title' => t('Do something fantastic!'),
      'description' => t('Allow user role to do something totally awesome'),
    ),
  );
}

This will create a custom user permission on the permissions page called ‘Do something fantastic!’. Just click on the roles that should have access and now your page is limited to those roles.

Comments are closed.