Last active
January 30, 2024 14:51
-
-
Save knolaust/55ddcb3396da06a56f8485182ce930c9 to your computer and use it in GitHub Desktop.
Add Page/Post slug to body class in WordPress
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 | |
/** | |
* 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