Skip to content

PHP: Hooks and filters

Kevin Van Lierde edited this page Jan 29, 2019 · 2 revisions

UserMgr provides a hook for permission and user group registration (permissions-hook), 1 hook for back-end (PHP) page access restriction, and 2 filters for front-end (CSS, JS) page access restriction.

page-access (hook)

Description: This hook is executed after the standard page restrictions are applied (by page name, or plugin id). If your plugin replaces a standard admin page (e.g. I18N replaces pages.php with load.php?id=i18n_base) or needs additional parameter checks, you can use the $usermgr->restrict_access function here or define your own logic.

Example: (make i18n work with the permission 'access_pages.php')

function i18n_base_pages_access() {
  $usermgr = usermgr();
  $current_user = current_user();
  if ($current_user->cannot('access_pages')) {
    $usermgr->restrict_access();
  }
}

if (myself(false) === 'pages.php')
  add_action('page-access', 'i18n_base_pages_access');

permissions-hook (hook)

Description: Use this hook to register additional user permissions and user groups.

Example: (register 2 permissions and a new user group)

function myfunction($current_user, $style) {
  $usermgr = usermgr();
  
  // register some custom permissions
  $usermgr->register('permissions', 
    'my_permission1',
    'my_permission2'
  ));
  
  // register a custom group, that extends 
  $my_group = UsrGroup::create('my_group');
  $my_group->extend($usermgr->groups->get('admin'));
  $my_group->deny('access_settings.php');
}
add_action('permissions-hook', 'myfunction');

permissions-css (filter)

Description: This hook allows adding extra CSS style rules based on usermgr conditions. Your function must return $style;.

Example: (hiding the top-navigation pages tab with CSS)

function myfunction($current_user, $style) {
  if ($current_user->cannot('access_pages'))
    $style .= ' #nav_pages { display: none; }';
  return $style;
}
add_filter('permissions-css', 'myfunction');

permissions-js (filter)

Description: This hook allows adding extra JS code based on usermgr conditions. Your function must return $script;.

Example: (hiding the top-navigation pages tab with JS)

function myfunction($current_user, $script) {
  if ($current_user->cannot('access_pages'))
    $script .= ' document.getElementById(\'nav_pages\').style.display = \'none\';';
  return $script;
}
add_filter('permissions-js', 'myfunction');