0

How can I add a unique class for WP admin pages (including trash)

ex. URL wp-admin/edit.php?post_status=trash&post_type=locations

  • Would you like to add the class the the body html tag ? – Lucien Dubois Feb 7 at 3:57
  • Can I ask why you need this? My first impression is that if you need this you're doing something wrong. – Jacob Peattie Feb 7 at 12:13
  • I want to be able to add some css on per page basis – Shae Feb 7 at 14:16
1

You can hook to admin_body_class:

add_filter( 'admin_body_class', 'set_admin_page_as_body_class' );

/**
 * Create a body class based on the current admin page.
 *
 * @param string $classes The current admin body classes.
 * @return string
 */
function set_admin_page_as_body_class( $classes ) {
    /**
     * For safety, I always check for get_current_screen before I use it.
     * May not be needed for how late `admin_body_class` is filtered.
     */
    if ( ! function_exists( 'get_current_screen' ) ) {
        return $classes;
    }

    $screen = get_current_screen();

    /**
     * Build an array of the parts you want.
     *
     * $screen->base gives you the page pase, so "edit.php"'s base is "edit"
     * get_query_var: https://codex.wordpress.org/Function_Reference/get_query_var
     */
    $vars   = [
        $screen->base,
        get_query_var( 'post_type' ),
        get_query_var( 'post_status' ),
        // etc.
    ];

    // array_filter will remove any "empty" elements.
    $vars  = array_filter( $vars );
    $class = implode( '-', $vars );

    // Don't add our class more than once.
    if ( false !== strpos( $classes, $class ) ) {
        return $classes;
    }

    $classes .= " {$class} ";
    return $classes;
}

Edit: your example URL, wp-admin/edit.php?post_status=trash&post_type=locations would generate a class like edit-locations-trash

  • 1
    Perfect! @phatskat exactly what I was trying to do. Thank you. – Shae Feb 7 at 14:55

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.