Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

WordPress Body Classes


WordPress
David Egan

Adds extra body classes by hooking into the ‘body_class’ filter.

<?php
/**
 * Add page slug to `body_class()` classes if it doesn't exist
 * & add user role to body class
 *
 * Hooks into the `body_class` filter.
 *
 * @package UserHelpers
 * @param  array $classes Passed in from the body_class filter
 * @return array $classes Extra classes added
 *
 */
function carawebs_body_class( $classes ) {

  // Add post/page slug
  // ---------------------------------------------------------------------------
  if ( is_single() || is_page() || is_archive() && !is_front_page() || is_bbpress() ) {

    if (!in_array(basename( get_permalink() ), $classes) ) {

      $classes[] = basename( get_permalink() );

    }

    // Check to see if the user is logged in, and if they are, add their role to the body class.
    // -------------------------------------------------------------------------
    if( is_user_logged_in() && !is_front_page() ){

      $current_user       = wp_get_current_user();  // Current user object
      $current_user_id    = $current_user->ID;      // Current user ID
      $user_role          = carawebs_get_user_role( $current_user_id );
      $user_role          .= '-role'; // append modifier to avoid confusion with pages having same name
      $classes[]          = $user_role;

    }

  }

  return $classes;

}
add_filter('body_class', 'carawebs_body_class');

comments powered by Disqus