1

I'm trying to add a class to the body tag using PHP. I have it working to a point but I'm not sure about the syntax of checking for multiple pages. Hope this will explain better. I currently have some code in the head of each page to name each individual page:

<?php 
$page = 'home';
?>

home is replaced with the name of the page e.g about, contact etc

On my body tag I have the following:

<body class="<?php echo ($page == 'home' ? 'home':'');?>">

This adds the class of 'home' to the body. This code is sat within a header.php includes file so I need it to check through all pages and then add the right class. So something like:

<?php echo ($page == 'home' ? 'home':'');?>
<?php echo ($page == 'about' ? 'about':'');?>

etc

Hope this makes some sense. I'm guessing the answer is quite simple (if you know how) but I'm no developer so my experience of PHP is very limited.

Any help would be appreciated.

1 Answer 1

4

If you have

<?php 
$page = 'home';
?>

or

<?php 
$page = 'about';
?>

etc.

at the top of each page, then it will suffice to simply write:

<body class="<?php echo $page; ?>">
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.