Skip to content

Instantly share code, notes, and snippets.

@knolaust
Last active January 30, 2024 14:51
Show Gist options
  • Save knolaust/55ddcb3396da06a56f8485182ce930c9 to your computer and use it in GitHub Desktop.
Save knolaust/55ddcb3396da06a56f8485182ce930c9 to your computer and use it in GitHub Desktop.
Add Page/Post slug to body class in WordPress
<?php
/**
* Adds the current page or post slug as a class to the body tag in WordPress.
*
* This function is useful for applying page-specific CSS styles. It checks if
* the current view is a singular page and then adds the post's slug as a class
* to the body tag, making it easier to target with CSS.
*
* Gist Keywords: wordpress, theme, slug, css, body class
*
* @param array $classes Existing classes applied to the body tag.
* @return array Modified array of classes with the added page or post slug.
* @author Knol Aust
*/
// Define a function to add the page slug to the body class
function knolaust_add_slug_to_body_class($classes) {
global $post; // Access post data
if (is_singular() && !empty($post)) {
$classes[] = $post->post_name; // Add post slug to classes
}
return $classes; // Return modified classes
}
// Hook the function into the 'body_class' filter
add_filter('body_class', 'knolaust_add_slug_to_body_class');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment