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

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?

Read More

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); ?>>

Related posts

1 comment

  1. 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); ?>>
    

Comments are closed.