Add Page/Post slug to body class in WordPress

01/30/2024
Back to Gists
<?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');