Jannis
Jannis

Reputation: 17315

WordPress: How can I add extra classes via variables when using body_class()?

I am trying to add some dynamically (based on the URI) created class names into the standard body_class() statement.

The wordpress codex mentions to put the class into the brackets while using the body_class('add-class-here')

however I have 2 variables that I need to echo out inside the body class="" so I tried doing it as follows:

<?php
$url = explode('/', $_SERVER['REQUEST_URI']);
$dir = $url[2] ? $url[2] : 'home';
$subdir = $url[3] ? $url[3] : '';
?>

<body <?php body_class(<?=$dir?><?=($subdir?' ':'')?><?=$subdir?>); ?>>

This however results in a PHP error thus breaking the page.

I tried to add body_class($dir) and while it works, when adding the second variable $subdir it fails.

eg. body_class($dir($subdir?' ':'')$subdir) results in: Parse error: syntax error, unexpected T_VARIABLE

the ($subdir?' ':'') is only there to add a space between class names if $subdir is set.

Any ideas how I can add my variables into the body class while keeping the standard generated classes of the body_class() function?

Thanks for reading.

Upvotes: 0

Views: 1353

Answers (1)

code_burgar
code_burgar

Reputation: 12323

$path = (isset($subdir) && !empty($subdir)) 
  ? $dir . ' ' . $subdir 
  : $dir . $subdir;
body_class($path);

Upvotes: 3

Related Questions