Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Check for Class in body_class() in Wordpress

Tags:

php

wordpress

Within Wordpress header.php, I have

<body <?php body_class($class); ?>>

How do check to see if a specific class exists, and then load markup as a result? For ex.

<body class"home logged-in">

<?php if $class == 'home' ?>
    <div class="home"></div>
<? else : ?>
    <div class="internal-page"></div>
<? endif; ?>

Thanks!

like image 548
Yasir Avatar asked Feb 22 '13 21:02

Yasir


People also ask

How do I find Page class in WordPress?

Right click on that page (anywhere) and select “Inspect Element“. Search inside the site's markup for the body tag. It should be one of the first elements in the source. You'll see it has many classes.

What does Body_class () function actually do in WordPress?

This function gives the body element different classes and can be added, typically, in the header.

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

To add your own class to this, you can pass an argument in to the function, like so: <body <? php body_class( 'my-class' ); ?>> This would add a body class of my-class on each page of your WordPress site.

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.


2 Answers

If you really, really need to use different markup based on the body_class classes, then use get_body_class

$classes = get_body_class();
if (in_array('home',$classes)) {
    // your markup
} else {
    // some other markup
}

But there are probably better ways to do this, like @Rob's suggestion of Conditional Tags. Those map pretty closely to the classes used by body_class.

like image 176
s_ha_dum Avatar answered Oct 10 '22 00:10

s_ha_dum


You can access body_class with a filter add_filter('body_class', function ...) however, I think you are taking the wrong approach. Why not just use css for what you need? For example, .home>div { /* home styles */ }

Or you can load a different stylesheet

add_filter('body_class', function($classes) {
    if (in_array('home', $classes)) {
        wp_enqueue_style('home');
    }
    return $classes;
});
like image 37
Rob Avatar answered Oct 10 '22 02:10

Rob