Craig Simpson

Web developer from Moray, Scotland

Add the day of the week as a body class to your WordPress website.

25th August 2015

No Comments

I’m a regular in the GenesisWP Slack channel, and love tackling little code problems or offering support where I can. One such conundrum came from a question by Paul Smart, who had a client ask him to add different styling to elements on the website depending on the day of the week.

By filtering the body class, and using the PHP Date function, we can add the day of the week to the <body> tag, and then use it to style elements accordingly.

1add_filter( 'body_class', 'prefix_add_day_of_the_week_to_class_names' );
2/**
3 * Add the current day of the week to the body class names.
4 *
5 * @param array $classes The current body class names.
6 *
7 * @return array The updated body class names.
8 */
9function prefix_add_day_of_the_week_to_class_names( $classes ) {
10 $classes[] = strtolower( date( 'l' ) );
11 return $classes;
12}

The PHP date function gives us the day of the week, and we can make use of the strtolower() function to make sure that it’s in lower case and follows the standard formatting of other body classes.

Once this snippet is in place, we can utilise it in our CSS file to change styling depending on the day of the week, like so:

1.monday .entry-title {
2 color: red;
3}
4 
5.tuesday .entry-title {
6 color: blue;
7}
8 
9.wednesday .entry-title {
10 color: green;
11}

Leave a Reply

Your email address will not be published. Required fields are marked *