How to Check for Class in body_class() in Wordpress

前端 未结 3 884
野性不改
野性不改 2020-12-15 22:48

Within Wordpress header.php, I have

>

How do check to see if a specific class exists, and th

相关标签:
3条回答
  • 2020-12-15 23:28

    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'];
    }
    
    0 讨论(0)
  • 2020-12-15 23:32

    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.

    0 讨论(0)
  • 2020-12-15 23:36

    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;
    });
    
    0 讨论(0)
提交回复
热议问题