Controlling file and content includes with body classes in WordPress

Posted on 5th February, 2015 Leave a Comment

I use this a lot, using a body class to insert stuff is awesome. Whether I’m using it to insert some HTML, control some CSS or including a relative file to a existing page.
This also helps when having sites with multiple plugins can effect the performance so by simply adding a body class to include the file is my favorite way of doing it.


in the header.php find the body tag and include a call to the classes.

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

Then above our stylesheets add this. I’m adding it above the stylesheets because I want to potentially use this to include plugin stylesheets.

<?php $classes = get_body_class(); // INCLUDE THE BODY CLASSES ?>

Any other page template file

Include a function to add our body classes, I like to add this at the very top of each template file.


## add a custom body class 
add_action( 'body_class', 'add_my_bodyclass'); 
function add_my_bodyclass( $classes ) { 
	$classes[] = 'notitle'; 
	$classes[] = 'popup'; /* EACH NEW CLASS REQUIRES IT'S OWN LINE */
	return $classes; 

header.php or footer.php

Next you’ll need to check for the body class to include whatever file that’s needed in relation to that page. So for this i’m going to stick to the most simple example and include javascript in the footer of the theme.

<?php	if (in_array('popup',$classes)) { ?>
	<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/javascript/jquery.popup.min.js"></script>
<?php };?>

It really is as simple as that. The snip above checks through the list of $classes added to the current page and if that class exists then it’ll include this file.


We can also use this to add conditional individual styles to our stylesheet. So say we have pages where a title isn’t necessary. Using the example above “notitle” is added.
I can then use this in the css like to remove the post title.

.notitle h1 {
	display: none;

Hope you’ve found this post useful.


Leave a Comment

To preserve code added to a comment you can wrap your code in short tags
by using [square brackets]:

  1. PHP use - [php] <?php code here ?> [/php]
  2. CSS use - [css] #code-here {} [/css]
  3. HTML use - [html] <div> code here </div> [/html]
  4. JS use - [js] $(".codeHere") [/js]