Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a custom class name to Wordpress body tag?

Tags:

I'd like to place a directive in my theme's functions.php file which appends a classname to the wordpress body tag. Is there a built-in API method for this?

For example, my body tag code is...

<body <?php if(function_exists("body_class") && !is_404()){body_class();} else echo 'class="page default"'?>>

And it results in the following being written to the body tag (depending on the context in which the page is presented (page, post, logged-in, etc)

<body class="home blog logged-in"> 

Depending on the child theme I'm using at the time, I want it to be...

<body class="home blog logged-in mychildthemename"> 
like image 773
Scott B Avatar asked Mar 17 '10 21:03

Scott B


People also ask

How do I add a custom class to the body tag in WordPress?

The body_class() function in WordPress makes this very easy for us by automatically adding a bunch of appropriate classes to the body tag of our website. One such example would be the logged-in class that is added to the body tag if a logged-in user is viewing the page.

Can I add class to body tag?

We used the add() method to add a class on the body object. We can access the body element on the document object. If the class is already present on the body element, it won't get added twice. You can pass as many classes to the add() method as necessary.


1 Answers

You can use the body_class filter, like so:

function my_plugin_body_class($classes) {
    $classes[] = 'foo';
    return $classes;
}

add_filter('body_class', 'my_plugin_body_class');

Although, obviously, your theme needs to call the corresponding body_class function.

like image 200
Richard M Avatar answered Nov 09 '22 01:11

Richard M