Web Design & Development

Add Time, Date And Day Classes To Body Tag

You can add current time, date and day to body classes via a specific function, outlined below. To do this, you can add the following (without the opening PHP tag) to your functions.php file. Grab the code from the Gist, or below.

<?php

// Add the times and days to the body classes
// e.g., date-day-wednesday date-ymd-20170614 date-month-june time-military-1317 time-pm time-early-afternoon
add_filter( 'body_class', 'add_date_info_to_class_names' );
function add_date_info_to_class_names( $classes ) {
	// current day of week name
	$classes[] = 'date-day-' . strtolower(date_i18n('l'));
	// current full date YYYYMMDD
	$classes[] = 'date-ymd-' . strtolower(date_i18n('Ymd'));
	// current month name
	$classes[] = 'date-month-' . strtolower(date_i18n('F'));
	// current military time HHMM
	$classes[] = 'time-military-' . strtolower(date_i18n('Hi'));
	// check hour and add am or pm class
	if ( date_i18n('H') >= 12 ){
		$classes[] = 'time-pm';
	} else {
		$classes[] = 'time-am';
	}
	// check hour and add time of day descriptor
	if (preg_match("/(00|01|02)/i", date_i18n('H'))){
	  $classes[] = 'time-early-night';
	}
	elseif (preg_match("/(03|04|05)/i", date_i18n('H'))){
	  $classes[] = 'time-late-night';
	}
	elseif (preg_match("/(06|07|08)/i", date_i18n('H'))){
	  $classes[] = 'time-early-morning';
	}
	elseif (preg_match("/(09|10|11)/i", date_i18n('H'))){
	  $classes[] = 'time-late-morning';
	}
	elseif (preg_match("/(12|13|14)/i", date_i18n('H'))){
	  $classes[] = 'time-early-afternoon';
	}
	elseif (preg_match("/(15|16|17)/i", date_i18n('H'))){
	  $classes[] = 'time-late-afternoon';
	}
	elseif (preg_match("/(18|19|20)/i", date_i18n('H'))){
	  $classes[] = 'time-early-evening';
	}
	elseif (preg_match("/(21|22|23)/i", date_i18n('H'))){
	  $classes[] = 'time-late-evening';
	}
	return $classes;
}

Need Help?

Tell us about your project!

  • Date Format: MM slash DD slash YYYY
  • This field is for validation purposes and should be left unchanged.
Previous Post
FreshySites Binghamton Office Is Moving!
Next Post
Make Header Static On Page Until It Becomes Fixed

Related Articles

Menu
Google Rating
5.0
Based on 56 reviews
×
Get a Quote