WordPress: Add the Page Slug to Body Class

01/30/2024
Back to Gists
<?php
/**
 * Adds a custom class to the body tag in WordPress based on post type and name.
 *
 * This function modifies the classes applied to the body tag of a WordPress page.
 * It adds a class that combines the post type and the post's slug (name).
 * This can be useful for applying specific CSS styles to different pages or posts.
 *
 * Gist Keywords: wordpress, functions, body, css, styles
 *
 * @param array $classes The existing array of classes for the body tag.
 * @return array The modified array of classes with the additional custom class.
 */
function knolaust_snippet_add_slug_body_class( $classes ) {
    // Access the global $post variable to get information about the current post.
    global $post;

    // Check if the $post object is set to avoid errors in cases where it's not.
    if ( isset( $post ) ) {
        // Append a new class to the $classes array.
        // This class is a combination of the post type and the post slug (name).
        $classes[] = $post->post_type . '-' . $post->post_name;
    }

    // Return the modified array of classes.
    return $classes;
}

// Add the above function to the 'body_class' filter hook.
// This ensures that our custom function is called whenever WordPress generates the class attribute for the body tag.
add_filter( 'body_class', 'knolaust_snippet_add_slug_body_class' );
?>