Skip to content

Instantly share code, notes, and snippets.

@joshuaiz
Last active April 22, 2018 01:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshuaiz/619dcb5936b839972356a75c06efe6a8 to your computer and use it in GitHub Desktop.
Save joshuaiz/619dcb5936b839972356a75c06efe6a8 to your computer and use it in GitHub Desktop.
Plate WordPress body class function: adds more classes to your WordPress posts + pages to help with CSS
<?php
// Body Class functions
// Adds more slugs to body class so we can style individual pages + posts.
// In your SCSS/CSS, use .page-yourslug {} to add styles for that page or post.
add_filter( 'body_class', 'plate_body_class' );
function plate_body_class( $classes ) {
global $post;
if ( isset( $post ) ) {
/* $classes[] = $post->post_type . '-' . $post->post_name; *//*Un comment this if you want the post_type-post_name body class */
$pagetemplate = get_post_meta( $post->ID, '_wp_page_template', true);
$classes[] = sanitize_html_class( str_replace( '.', '-', $pagetemplate ), '' );
$classes[] = $post->post_name;
}
if (is_page()) {
global $post;
if ( $post->post_parent ) {
# Parent post name/slug
$parent = get_post( $post->post_parent );
$classes[] = $parent->post_name;
# Parent template name
$parent_template = get_post_meta( $parent->ID, '_wp_page_template', true );
if ( !empty($parent_template) )
$classes[] = 'template-'.sanitize_html_class( str_replace( '.', '-', $parent_template ), '' );
}
// If we *do* have an ancestors list, process it
// http://codex.wordpress.org/Function_Reference/get_post_ancestors
if ($parents = get_post_ancestors( $post->ID )) {
foreach ( (array)$parents as $parent ) {
// As the array contains IDs only, we need to get each page
if ( $page = get_page($parent) ) {
// Add the current ancestor to the body class array
$classes[] = "{$page->post_type}-{$page->post_name}";
}
}
}
// Add the current page to our body class array
$classes[] = "{$post->post_type}-{$post->post_name}";
}
return $classes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment