Drupal - How can I detect if the current viewed page is administrative?

This can be done with path_is_admin(current_path()).

For example, the following hook implementation can be used.

function mymodule_init() {
  if (user_access('administer modules') && path_is_admin(current_path())) {
      drupal_set_message(t('Message'));
  }
}

Daniel's answer is correct for determining if the current path is "administrative," but if you want to more directly check if the administration theme is being used (your question seems a bit vague as to which you're looking for), you can do…

global $theme;
if ($theme === variable_get('admin_theme', 'seven')) {
  // …
}

…though this is likely to fail if you try to run it too early in the bootstrap process, namely before $theme is defined.


For those looking for the Drupal 8 method:

if (\Drupal::service('router.admin_context')->isAdminRoute()) {
  // …
}

(Tested with a preprocess function in 8.7.5 and used in a core-patch in 8.0)

Tags:

7