Add a custom class name to Wordpress body tag?

前端 未结 7 1552
忘掉有多难
忘掉有多难 2021-02-07 03:29

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 exampl

相关标签:
7条回答
  • 2021-02-07 03:37

    In case you're trying to add classes to the body tag while in the Admin area, remember to use the admin_body_class hook instead. Note that it's a filter which works slightly different since it passes a string of classes rather than an array, so your code would look like this:

    add_filter('admin_body_class', 'my_admin_body_class');
    function my_admin_body_class($classes) {
        return $classes . ' my_class';
    }
    
    0 讨论(0)
  • 2021-02-07 03:38

    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.

    0 讨论(0)
  • 2021-02-07 03:46

    Simply edit your theme's header.php and change the class there (manually or according to some preset logic rules).

    0 讨论(0)
  • 2021-02-07 03:47

    To add more classes to the filter, just add another line that adds another value in to the array:

    add_filter( 'body_class','my_body_classes' ); function my_body_classes( $classes ) {

    $classes[] = 'class-name';
    $classes[] = 'class-name-two';
    
    return $classes;
    

    }

    0 讨论(0)
  • 2021-02-07 03:50

    If you just want to add class based on your page template note that WP now automatically adds per-template class to body tag.

    0 讨论(0)
  • 2021-02-07 03:51

    You can also use it directly inside the WP body_class function which will append the string inside body class.

    eg.

    $class="custom-class";
    <body <?php body_class($class); ?>>
    

    http://codex.wordpress.org/Function_Reference/body_class

    0 讨论(0)
提交回复
热议问题