I want to add a extra unique class in body tag so that it will come only for the anonymous user.
How to add it?
I want to add a extra unique class in body tag so that it will come only for the anonymous user.
How to add it?
The proper way to do this is in a preprocess hook:
function MYTHEME_preprocess_html(&$vars) {
if (user_is_anonymous()) {
$vars['classes_array'][] = 'foo-class';
}
}
Don't try to make this decision in a template file, you'll find it doesn't work properly when you have caching enabled. Or it'll break your caching entirely for the page.
template_preprocess_html
and either adds logged-in
or not-logged-in
, so a class should already be there.
– mpdonadio♦
Oct 14 '15 at 15:23
Core already does this for you. If you examine includes/theme.inc, you will find the implementation for template_preprocess_html()
which is run by default before module and theme specific versions. In it is this code blip
function template_preprocess_html(&$variables) {
// ...
$variables['classes_array'][] = $variables['logged_in'] ? 'logged-in' : 'not-logged-in';
// ...
}
So, there are already body classes, logged-in
and not-logged-in
, added for you. If those classes is not there, something is altering the $variables['classes_array']
in a naughty way.