Using the Date Format Chosen by the User Instead of Hard-Coding Your Own in the WordPress Theme

WordPress has a setting under the admin panel where blog owners can indicate how dates should be displayed for blog posts and comments made to the blog. The setting isn't very useful though when the date format is hard coded into the theme. Instead of making users edit the theme files, let's take advantage of the WordPress setting.

Hard-coded Date Format

WordPress theme developers seem to utilize code like the following when displaying content that has dates, such as posts and comments:

<?php the_time("M d, Y"); ?>

However, as discussed last week (Choosing the Date Format in WordPress Themes: Let's Give Control Back to the User), the format inside the_time() function prevents users from changing the date format, unless they modify the theme files. Well, we can't use the_time() function without some kind of format. Leaving it blank only gives the time a post was published. So what about the_date() function?

At first glance, the_date() seems to work fine. But, upon closer inspection the function has some "odd" behavior when a page has multiple posts from the same date—only the first post gets the date. The rest have a blank space where the date should be.

Alternate Solution

For the comments section of our blog, the comment_date() function works perfectly. The date is always displayed; even if there are multiple comments on the same day. To use the date format set under the WordPress admin panel, we just need to leave the parameters blank.

<?php comment_date(); ?>

Maintaining the user's format for posts is a little trickier. To avoid the issue with multiple posts on the same day, we'll use the_time() function. The get_options() function can then be used to get the date format from the admin panel.

<?php the_time(get_option('date_format')); ?>


Now, there may be areas where it makes sense to hard code the date format. When someone's viewing the blog archive by month for example, the page header text only needs to show the month and year. But the majority of the dates can utilize the_time() function in conjunction with get_option()…or the comment_date() function for comments posted to the blog.


There are currently no comments.

Leave a Comment