Question

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.

Was it helpful?

Solution

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' );
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top