如何在Wordpress中使用body_class为body标签添加CSS类


How to add CSS class to body tag in Wordpress using body_class

我正在Wordpress中构建一个自定义主题,当URL以?checklist-view=1结尾时,我需要为body标签添加一个CSS属性

我下面的代码有什么问题,因为没有添加全屏?

我明白,我需要使用超全局$_GET,但我是完全新的PHP。

是否有一个更简单的方法来做到这一点与body_class模板标签(像我下面尝试),或者这是需要更复杂的PHP

EDIT:将$class设置为字符串而不是数组。

<!doctype html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo('charset'); ?>" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=0">
    <title>Process Street <?php wp_title(); ?></title>
    <link rel="profile" href="http://gmpg.org/xfn/11" />
    <link rel="stylesheet" href="<?php echo get_stylesheet_uri(); ?>" type="text/css" media="screen" />
    <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
    <!--[if lt IE 9]>
    <script src="<?php echo get_stylesheet_uri(); ?>bower_components/html5shiv/dist/html5shiv.js"></script>
    <![endif]-->
    <?php wp_head(); ?>
</head>
<?php
//?checklist-view=1
$is_checklist = $_GET['checklist-view'];
$class= 'fullscreen';
if($is_checklist == '1') {
    echo $class;
}
?>
<body <?php body_class($class); ?>>

您不应该将类echo,而是应该将其分配给稍后传递给body_class()的变量。我也会检查是否设置了checklist-view,以避免错误:

<?php
$is_checklist = $_GET['checklist-view'];
if ( !empty( $is_checklist ) && $is_checklist === '1') {
    $class= 'fullscreen';
} else {
    $class = '';
}
?>
<body <?php body_class($class); ?>>

您也可以使用三元操作符实现相同的目的:

$checklist = $_GET['checklist-view'];
$class = ( !empty( $checklist ) && $checklist === '1') ? 'fullscreen' : '';
?>
<body <?php body_class($class); ?>>