dounianluo0086 2015-10-22 21:14
浏览 92
已采纳

如何使用body_class将CSS类添加到Wordpress中的body标签

I'm building a custom theme in Wordpress and I need to add a CSS attribute to the body tag when the URL ends in ?checklist-view=1

What is wrong with my code below, since no fullscreen is being added?

I understand that I need to use the superglobal $_GET, however I'm completely new to PHP.

Is there an easier way to do this with the body_class template tag (like im trying below) or is this something that would require more complicated PHP

EDIT: Changed $class to equal a string and not have it set to an array.

<!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); ?>>
  • 写回答

1条回答 默认 最新

  • duancaishi1897 2015-10-22 21:24
    关注

    You shouldn't echo the class but, rather, you should just assign it to the variable to be passed to body_class() later. I'd also check whether or not checklist-view is set, to avoid errors:

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

    You can also achieve the same thing with the ternary operator:

    $checklist = $_GET['checklist-view'];
    $class = ( !empty( $checklist ) && $checklist === '1') ? 'fullscreen' : '';
    ?>
    
    <body <?php body_class($class); ?>>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制