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!
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.
This function gives the body element different classes and can be added, typically, in the header.
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.
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.
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
.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With