How to Check for Class in body_class() in Wordpres

2019-01-23 18:01发布

问题:

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!

回答1:

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.



回答2:

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;
});


回答3:

I have had the same problem as I created pages using different templates but a custom sub-menu needed to be the same on each pages.

I tried this one first what is failed

<body <?php body_class( 'extra-class' ); ?>>

The extra classes was added to the body tag but when I run the error log then it was not in the classes array. So I was sure it was added later to the body tag.

This solution worked for me:

functions.php

$GLOBALS['extraBodyClass'] = '';

In the template file

<?php $GLOBALS['extraBodyClass'] = 'extra-class' ?> - very first line in the template file

<body <?php body_class( $GLOBALS['extraBodyClass'] ); ?>> - after the template name declaration

In the header.php file

$classes = get_body_class();
if($GLOBALS['extraBodyClass']){
   $classes[] = $GLOBALS['extraBodyClass'];
}


标签: php wordpress