The standard page class in Wordpress looks something like this;

<body class="page-template page-template-page-templates page-template-page-standard 
page-template-page-templatespage-standard-php page page-id-7 page-parent">

which if you ask me, is a bit bloated, I mean who is going to set up a css class .page-template-page-templatespage-standard-php ? And I do like human readable code.

So my question is how to rewrite the core function body_class()?

This is an 'answer to my own question', a bit topsy-turvy. I looked for this information and didn't find it out there so hopefully useful to someone.

1 Answer 1


And the answer is like this; I figured the most useful bits for me was something that read like this;

<body class="page my-page page-id-28 template-mypage">

where page is the post type, mypage is the page slug, then the id and finally an elegant form of the template. (my templates are all of the form page-templates/page-mypage.php so you'll need to put your own structure in here - most of the code is cleaning up the template slug.

Put this into functions.php

//Modify body_class()
function modify_body_class( $classes ) {

global $post;

// Empty class array
$classes = array();

if (is_front_page()) {
    $classes[] = 'home';

// add post type
// add slug
// Add page ID
// Add template slug (first sanitise)
$template_slug = get_page_template_slug();
if ($template_slug) {
    $template_slug = str_replace('page-templates/', "", $template_slug);
    $template_slug = str_replace('.php', "", $template_slug);
    $template_slug = str_replace('page-', "template-", $template_slug);
} else {
    $template_slug = null;

if ( isset( $post ) ) {
    $classes[] = $post->post_type;
    $classes[] = $post->post_name;
    $classes[] = $post->post_type .'-id-'.$post->ID;
    $classes[] = $template_slug;
return $classes;

add_filter( 'body_class', 'modify_body_class' );
  • 3
    That'll do it. But I wouldn't suggest removing any class from the body. Some plugins/themes depend on them.
    – Johansson
    Commented Jul 12, 2017 at 17:48
  • There's quite a discussion there. 1. It's my theme (and I'll cry if I want to) so I know where my theme interacts and 2. I take your point about plugins though I have yet to come across one that uses the frankly ugly template derived classes. I have yet to use this with archives, the search or the 404 so it may be I feel the need to put those back in. I just like the control it gives.
    – Chris Pink
    Commented Jul 13, 2017 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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