views:

182

answers:

1

Hi,

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.

+1  A: 
$path = (isset($subdir) && !empty($subdir)) 
  ? $dir . ' ' . $subdir 
  : $dir . $subdir;
body_class($path);
code_burgar
Thanks, this somewhat works however if `subdir` is empty there is a trailing space inside the `classes=""`eg.: if `$dir = class1``$subdir = class2` then`class="class1 class2"` but if `$subdir = ""` then `class="class1 "`I'd love to be able to just remove that trailing white space which is why I had originally added the if statement `($subdir?' ':'')` so that only if $subdir is set a space gets inserted.Any idea how I can arrange for that?Thanks for the feedback!
Jannis
@Jannis: This should fix it
code_burgar
Thank you! It did indeed fix it. Thanks again.
Jannis