In drupal 7 we have options to set default theme & admin theme. There are limitations, Admin theme will be available for roles which has access permission for admin theme. But in case if we have conditions to set specific theme for specific page based on user roles or specifying theme for particular node types, drupal core will not provide options to do these. We do have module available for this purpose - ThemeKey. But we can achieve by using drupal hooks also.
In this post I am going to explain how we can change particular theme for different pages based on various conditions. Let’s take following scenarios.
- Set admin theme for node edit pages for manager role users
- Set default theme for node/add/article pages for manager role users
Note : By default manager role is not set admin theme.
Drupal 7 provides hook_custom_theme() hook to do these functionality. Let’s create module called dynamic_theme. Check implementation of hook_custom_theme() for above scenarios.
Scenario 1 : Set admin theme for node edit pages for manager role users
/** * Implements hook_custom_theme(). */ function dynamic_theme_custom_theme() { // Load current user global $user; // Check current page is 'node/%nid%/nid' if(current_path() == 'node/%node/edit'){ // Check current user role is 'manager' $roles = $user->roles; if(in_array('manager',$roles)){ // return admin theme for these page return variable_get('admin_theme'); } } }
Scenario 2 : Set default theme for node/add/article pages for manager role users
/** * Implements hook_custom_theme(). */ function dynamic_theme_custom_theme() { // Load current user global $user; // Check current page is 'node/%nid%/nid' if(current_path() == 'node/add/article'){ // Check current user role is 'manager' $roles = $user->roles; if(in_array('manager',$roles)){ // return default theme for these page return variable_get('theme_default'); } } }
In case if we have multiple themes then return theme name in these function.
Note : The theme you want to activate must be enabled.