This handy snippet adds the page or post (or custom post type) slug to the page’s body class.
There are many scenarios where this proves to be very useful. One that I have found is targeting specific pages for CSS modifications.
For example, I often need to do specific changes or styling to the Contact page. Using the snippet below I am able to target using the class .page-contact
instead of .page-id-115
.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Add slug to body class | |
* | |
* @author Jared Atchison | |
* @link http://jaredatchison.com/code/ | |
* @param array $classes | |
* @return array | |
*/ | |
function ja_body_class_slug( $classes ){ | |
global $post; | |
if ( isset( $post ) ) | |
$classes[] = $post->post_type . '-' . $post->post_name; | |
return $classes; | |
} | |
add_filter( 'body_class', 'ja_body_class_slug' ); |
Questions, comments, or suggestion for improvement? Leave a comment on the GitHub Gist page.