Automatically change active Drupal 7 theme

What is the correct way to change the active theme of Drupal 7 programmatically? I used $custom_theme in Drupal 6, but it does not work in Drupal 7.

+7
source share
4 answers

You can use hook_custom_theme() :

 function mymodule_custom_theme() { if ($some_condition_is_true) { return 'my_theme'; } } 

If you need to create your choice on the way, the best way would be to override the theme callback for certain menu items. See here for an example .

+8
source

Although I'm not sure what the condition is when you want to change the theme, but if you want to change the theme based on the URL, such as node, taxonomic term, watch page, etc., then you can handle it using Context a module that will do this for you, and you donโ€™t even need to write a single line of code. Check this out: http://drupal.org/project/context

This is a very useful module and has nice integration with all known modules, such as panels, omega theme, delta, etc.

+1
source

The Drupal theme_default is the one you must set to switch themes using variable_set .

 variable_set('theme_default', 'your_theme_name'); 

You can change the default theme with hook_update_N if you already have a custom module installed. Also, make sure you call the code in hook_install to run it during installation, if you want to share your module with someone else and want to change the active theme during installation.

 /** * Implements hook_update_N(). */ function mymodule_update_7000() { $theme_list = array( 'bootstrap', 'mytheme', 'shiny', ); theme_enable($theme_list); $theme_default = 'mytheme'; // The below code would change the default active theme to 'mytheme' variable_set('theme_default', $theme_default); $admin_theme = 'shiny'; variable_set('admin_theme', $admin_theme); } 
0
source

While variable_set() will work for hook_install() or hook_update_N() , you should not use it in a module. Calling variable_set() empties the cache_bootstrap table, which is a serious performance hit on busy sites.

I would recommend ThemeKey if you do not need the full power of the context. However, contexts are easily exported for version control, although as far as I know there is no way to export ThemeKey rules.

0
source

All Articles