change the active Drupal 7 theme programmatically
Asked Answered
B

4

8

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

Bianca answered 16/11, 2011 at 11:40 Comment(0)
C
9

You can use hook_custom_theme():

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

If you need to base your selection on the path then the best way to go is to override the theme callback for particular menu router items. See here for an example.

Confederacy answered 16/11, 2011 at 11:56 Comment(0)
C
2

Although I am not sure what is the condition when you want to change the theme, but if you want to change the theme based on a url, node type, taxonomy term, view page etc then you can handle that using Context module which will do this for you and you don't even have 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 almost all famous modules like panels, omega theme, delta etc.

Concubine answered 2/5, 2012 at 2:33 Comment(0)
S
2

Drupal variable theme_default is the one you have to set to switch theme using variable_set function.

variable_set('theme_default', 'your_theme_name');

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

/**
 * 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);
}
Skaggs answered 14/3, 2015 at 15:37 Comment(0)
D
1

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

I would recommend the ThemeKey module if you don't need the full power of Context. However, contexts are easily exportable for versioning, while as far as I know there is no way to export ThemeKey rules.

Diazomethane answered 10/6, 2015 at 16:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.