1

I would need to get a custom body class, so that admin can set the class. At the moment I have field on page node type where I try to get it. The code what I have is below but it doesn't seem to work that smoothly. Something it prints two body classes (like this <body class="classes comes here" class="another set of classes">) It's in template.php and preprocess_html function.

$node = menu_get_object();
if ($node && isset($node->nid)) {

    $field_bClass = field_get_items('node', $node, 'field_bClass');

    if (!empty($field_bClass)) {
        $field_field_bClass_output = field_view_value('node', $node, 'field_bClass', $field_bClass[0], array(
            'type' => 'value'
        ));

        $vars['classes_array'][] = $field_field_bClass_output['#markup'];

    }
}

Is that corrrect and what should be done difrently?

  • Is it an admin page you're trying to alter? If so, does the template.php file you're adding this to belong to the same theme that's being used as the administration theme? – Clive May 10 '12 at 10:26
  • No, I'm trying to get the class printed on public pages. Admin just adds the custom body class name in admin pages. Then it should be printed out on public pages body class. – jörgen May 10 '12 at 10:32
  • Could it be that you're testing if (!empty($field___class)) {..., but don't have a variable called $field___class (there's one called $field_bClass instead)? – Clive May 10 '12 at 12:49
  • Sorry, thats just my copy & paste error here, so it's not that either. I have edited the code on first post. – jörgen May 10 '12 at 13:31
2
function TEMPLATE_preprocess_html(&$vars) {
    $node = menu_get_object();
    if ($node && isset($node->nid)) {
        $field_body_class = field_get_items('node', $node, 'field_body_class');

        if (isset($field_body_class[0]['value'])) {
            $vars['classes_array'][] = $field_body_class[0]['value'];
        }
    }
}

This is how it would look today in Drupal 7, assuming your field name is what it is in the example. (The difference with the other answer being instead of $vars['attributes_array']['class'][] using $vars['classes_array'][])

1
function TEMPLATE_alpha_preprocess_html(&$vars) {
  $node = menu_get_object();
    if ($node && isset($node->nid)){
    $field_bclass = field_get_items('node', $node, 'field_bclass');
    if (!empty($field_bclass)) {
        $vars['attributes_array']['class'][] = $field_bclass[0]['value'];
    }
}
}

I'm terrible at stacks code formatting, sorry.

  • This works really well, thanks for this bit. I've used the node class module which has always seemed very buggy to me and this method does the same thing only better. – Danny Englander Dec 30 '13 at 3:03
  • hm..i get this error : Undefined index: value – Yuri Apr 5 '15 at 8:20

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.