Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress | Add current time, date, and day to body classes via function
<?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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.