简体   繁体   中英

Add a custom class name to Wordpress body tag?

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 example, my body tag code is...

<body <?php if(function_exists("body_class") && !is_404()){body_class();} else echo 'class="page default"'?>>

And it results in the following being written to the body tag (depending on the context in which the page is presented (page, post, logged-in, etc)

<body class="home blog logged-in"> 

Depending on the child theme I'm using at the time, I want it to be...

<body class="home blog logged-in mychildthemename"> 

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.

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

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;

}

Try this..

    add_filter( 'body_class', 'custom_class' );
function custom_class( $classes ) {
    if ( !is_front_page() ) {
        $classes[] = 'example';
    }
    return $classes;
}

如果您只想根据页面模板添加类,请注意 WP 现在会自动将每个模板类添加到 body 标签。

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

只需编辑您的主题的 header.php 并更改那里的类(手动或根据一些预设的逻辑规则)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM