Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
I need to dynamically add a class to the body tag. The class value is provided for a node field.
This is what I did, but it is not fully working at all.
1) I added a field to the page content type called: field_body_class
2) I create the file: preprocess-html.inc in /sites/all/themes/omega_subtheme_2/preprocess and write this code:
<?
function omega_subtheme_2_alpha_preprocess_html(&$vars) {
if (arg(0) == 'node' && is_numeric(arg(1))) {
global $language;
$node = entity_load_unchanged('node', arg(1));
dpm( $node -> field_body_class['und'][0]['value']); //----->DPM #1
if (isset($node -> field_body_class['und'][0]['value']) && $node -> field_body_class['und'][0]['value']){
$vars['classes_array'][] = $node -> field_body_class['und'][0]['value'];
dpm($vars['classes_array']); //----->DPM #2
}
}
}
3) I create a page and fill the field_body_class field with myClass
4) DPM #1 shows the value: myClass
5) DPM #2: the array shows the element: myClass
But the class is not added to the body tag.
What am I missing here?
Comments
Comment #0.0
chefnelone CreditAttribution: chefnelone commentedmore info
Comment #0.1
chefnelone CreditAttribution: chefnelone commentedmore
Comment #1
Cellar Door CreditAttribution: Cellar Door commentedtake a look at: http://drupal.org/node/1471412 for guidance. I think you just need to use $vars['attributes_array']['class'][] = 'myclass'; instead
Comment #2
chefnelone CreditAttribution: chefnelone commentedThanks @Cellar Door, I get it working.
Comment #3.0
(not verified) CreditAttribution: commentedmore