I need to add a body class to the page when either a 403 or 404 error is served, I'm not sure how to go about this. I'm using logintoboggan which sets the default 403 page to toboggan/denied so don't want to override that and break functionality.

Any pointers would be great.


You can implement hook_preprocess_page(), and alter the value of $variables['body_classes'], which contains a list of CSS classes separated with a comma.
In Drupal 6, code similar to the following one should work:

function mymodule_preprocess_page(&$variables) {
  $headers = drupal_get_headers();

  if (preg_match('@HTTP/1\.[01]\x20+403@', $headers)) {
    $variables['body_classes'] .= 'error-403,';
  elseif (preg_match('@HTTP/1\.[01]\x20+404@', $headers)) {
    $variables['body_classes'] .= 'error-404,';

Replace "error-403" and "error-404" with the actual CSS classes you want to use.

This is similar to the code I have used in a module hosted on Drupal.org, which had to detect when Drupal 6 shown an "access denied" page, or a "page not found" page.

  • 1
    I would imagine that you could also use menu_get_active_item and compare its path to drupal_get_normal_path(variable_get('site_403', '')); if you knew that a 404 page had been set. – Angry Dan May 20 '13 at 11:59

For anyone working with Drupal 7, the function names and the way you pass variables are a bit different. The D7 solution for a 404 would look like this:

function MYMODULE_preprocess_html(&$variables) {
  $headers = drupal_get_http_header();

  if (isset($headers['status']) && $headers['status'] == '404 Not Found') {
    $variables['classes_array'][] = 'page-404';

The drupal_get_headers() function from D6 is now drupal_get_http_header() in D7. The values returned are structured a bit differently. You can view the contents of the array with "dpm($headers);" if you're using the devel module.

Finally, additional class variables can be added as elements of the $variables['classes_array'] by assigning them to an empty index, which will then be added to the html body tag via the template_process() function.

  • It can be directly "drupal_get_http_header("status");" if there is no need for all others header values – khaled_webdev Jul 5 '17 at 9:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.