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;
}
See our featured website design work

Check out some of the beautiful websites we’ve built for over 2,000 clients.

We offer WordPress support & maintenance

Shake the stress of ongoing maintenance with plans supported by our team of WordPress experts.

Related articles