How to Add body_class to Specific WordPress Page Templates

x theme
(Last Updated On: July 10, 2014)

body_class is a template tag in WordPress helping us to style our themes more effectively with CSS. This function automatically add different classes to your element. We usually use it inside header.php like:

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

If you’ll add above code to header.php, it will apply to all WordPress pages. But what you will do, if you want this body_class function to execute on specific pages. Following is the solution. Put it in functions.php.

//Add archive class to body tag of specific page templates (those that work as archives)
function add_archive_classes_to_page_templates($classes) {
if (is_page_template('news.php')) {
$classes[] = 'archive';
return $classes;
add_filter('body_class', 'add_archive_classes_to_page_templates');

Thanks to wptips for this code.

About the author


Leave a Reply

Your email address will not be published. Required fields are marked *