Forums

body_class(' php variables in here ') - how can I do this? (4 posts)

  1. jannisg
    Member
    Posted 1 month ago #

    Hi,

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

    The 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.

    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.

    Jannis

  2. mrmist
    Member
    Posted 1 month ago #

    You're already in the PHP angle tags when you're calling body_class, so you don't need another set of tags around your variables, just use them.

    body_class($dir) or similar.

  3. jannisg
    Member
    Posted 1 month ago #

    I tried that however as long as I add body_class($dir) it works, but when adding another 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.

    Thanks for the comment!

  4. jannisg
    Member
    Posted 1 month ago #

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

    body_class($path);

    Thanks to Codeburger @ StackOverflow.

Reply

You must log in to post.

About this Topic