WordPress adds helpful classes to the body tag and to each post, and you can add your own with the body_class and post_class filters. They make it easy to style a specific page or situation with CSS only.

Make sure your theme prints them

<body <?php body_class(); ?>>

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

Add custom body classes

function lotgrafix_body_classes( $classes ) {
    if ( is_user_logged_in() ) {
        $classes[] = 'lotgrafix-logged-in';
    }

    if ( is_singular() ) {
        $lotgrafix_object = get_queried_object();

        if ( $lotgrafix_object instanceof WP_Post ) {
            $classes[] = 'lotgrafix-slug-' . sanitize_html_class( $lotgrafix_object->post_name );
        }
    }

    if ( is_front_page() ) {
        $classes[] = 'lotgrafix-home';
    }

    return $classes;
}
add_filter( 'body_class', 'lotgrafix_body_classes' );

Add custom post classes

function lotgrafix_post_classes( $classes, $class, $post_id ) {
    if ( has_post_thumbnail( $post_id ) ) {
        $classes[] = 'lotgrafix-has-image';
    }

    if ( is_sticky( $post_id ) ) {
        $classes[] = 'lotgrafix-featured';
    }

    return $classes;
}
add_filter( 'post_class', 'lotgrafix_post_classes', 10, 3 );

Add a class in the admin

The admin filter works with a string, not an array.

function lotgrafix_admin_body_class( $classes ) {
    return $classes . ' lotgrafix-admin';
}
add_filter( 'admin_body_class', 'lotgrafix_admin_body_class' );

Use them in CSS

.lotgrafix-home .site-header {
    background: transparent;
}

.lotgrafix-has-image {
    display: grid;
    grid-template-columns: 200px 1fr;
}

Careful with page caching

Classes that depend on the visitor, like login status or device type, can be cached and shown to the wrong person if your site uses full page caching. Use them only for things that are the same for everyone, or load them with JavaScript.

«
»