Skip to content

Instantly share code, notes, and snippets.

@Soullighter
Last active August 1, 2016 12:49
Show Gist options
  • Save Soullighter/7f7bd77e343a42481e7545ad8dd281df to your computer and use it in GitHub Desktop.
Save Soullighter/7f7bd77e343a42481e7545ad8dd281df to your computer and use it in GitHub Desktop.
Wordpress
<?php
/* Get the Page Slug to Use as a Body Class, this will only return a value on pages! */
$class = '';
/* is it a page */
if( is_page() ) {
global $post;
/* Get an array of Ancestors and Parents if they exist */
$parents = wp_get_post_parent_id( $post->ID );
$id = ($parents) ? $parents: $post->ID;
/* Get the parent and set the $class with the page slug (post_name) */
$parent = get_post( $id );
$class = $parent->post_name;
}
?>
<!-- OR -->
<!-- By Ancestor -->
<?php
/* Get the Page Slug to Use as a Body Class, this will only return a value on pages! */
$class = '';
/* is it a page */
if( is_page() ) {
global $post;
/* Get an array of Ancestors and Parents if they exist */
$parents = get_post_ancestors( $post->ID );
$id = ($parents) ? $parents[count($parents) - 2]: $post->ID;
/* Get the parent and set the $class with the page slug (post_name) */
$parent = get_post( $id );
$class = $parent->post_name;
}
?>
<!-- Usage -->
<body <?php body_class( array( $class, "custom_class" ) ); ?>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment