body_class()根据不同的页面类型为body标签生成class

目录

描述

Themes have a template tag for the body tag which will help theme authors to style more effectively with CSS. The Template Tag is called body_class. This function gives the body element different classes and can be added, typically, in the header.php's HTML body tag.

body_class() 描述

用法

<body <?php body_class$class ); ?>

body_class() 用法

参数

How to pass parameters to tags with PHP function-style parameters

class

(string or array) (可选) One or more classes to add to the class attribute, separated by a single space.

默认值: null

body_class() 参数

示例

Implementation

The following example shows how to implement the body_class template tag into a theme.

The actual HTML output might resemble something like this (the About the Tests page from the Theme Unit Test):

In the WordPress Theme stylesheet, add the appropriate styles, such as:

Adding More Classes

By default, the only classes will be those described above.

To add more classes, the template tag's parameter can be added. For example, to add a unique class to the same template used above:

The results would be:

Add Classes By Filters

You can add additional body classes by filtering the body_class function.

To add the following to the WordPress Theme functions.php file, changing my_class_names and class-name to meet your needs:

To add a category class to single post pageviews and template files, add the following to the functions.php.

Add Sidebar Classes

You can add additional body classes by filtering the body_class function, but what if you want to add a class only when the sidebar.php file is being shown? Here's a working example you can post in your themes functions.php file to add a sidebar class to the output of body_class. From: Add CSS Class to body when Sidebar is Present

body_class() 示例

相关