Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPB Cup
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

How to Display Relative Dates in WordPress (2 Methods)

After running WordPress sites for many years, we’ve learned that small changes can make a big difference. One of these small but important details is how you show the date on your posts.

Most blogs usually show the exact date a post was published. But using relative dates like ‘2 days ago’ or ‘Yesterday’ can be better for readers. These dates quickly tell people how new and relevant your content is, which can make them more likely to read it.

The problem is that most WordPress themes don’t show dates this way by default. But don’t worry! We’ve figured out 2 easy ways to show relative dates on your WordPress site: one using a plugin and another using some simple code.

How to Display Relative Dates in WordPress

Why Display Relative Dates Over Absolute/Exact Dates?

Have you ever noticed how social media platforms like Facebook or Twitter show post dates as ‘2 hours ago’ or ‘3 days ago’ instead of exact dates? This is called a relative date format.

Unlike absolute dates (like ‘August 21, 2024’), relative dates in WordPress give your readers a quick sense of how fresh your content is.

Let’s look at an example. When visitors see a post dated ‘2 days ago’ rather than a specific date, they instantly know it is recent content. This way, readers can quickly tell which posts are new and worth checking out without having to think about today’s date or do any mental math.

However, it’s worth noting that relative dates aren’t suitable for every type of website.

For instance, if you’re running a historical blog or a site where precise dates are crucial, sticking with absolute dates might be better. The key is to consider your content type and audience preferences when deciding whether to add relative dates to your WordPress site.

With all that said, let’s take a look at 2 ways to add relative dates in WordPress. We’ve found a plugin that makes the process easy for you, but we’ve also come up with a code method that offers more control. You can use the quick links below to skip to your preferred method:

Method 1: Using Meks Time Ago Plugin (Free But Limited)

If you’re looking for a simple plugin to display relative times and dates in WordPress, then we have a great pick for you. Out of all the relative date plugins we’ve tried, Meks Time Ago is one of the easiest ones for beginners. Plus, it’s free and works with both classic and block themes.

To use Meks Time Ago, you can install and activate the WordPress plugin in your admin area.

After that, go to Settings » General in your dashboard. Scroll down, and you’ll find the plugin settings of Meks Time Ago.

The Meks Time Ago plugin settings

The first setting you must enable is where to apply the ‘time ago’ format to. Here, you need to pick ‘Date’ and ‘Time.’

You can also choose whether to apply this date format to posts that are not older than a certain number of minutes, hours, days, and months.

We decided to go with 12 months.

Configuring the Meks Time Ago plugin settings

Next, you can change where to place the word ‘ago’ in the date format.

We chose to keep it after the relative date because most people are familiar with this wording.

Choosing where to place the word ago in Meks Time Ago plugin page

Finally, you can replace the ‘ago’ word with a different term if needed. You can also just leave it blank.

Once you do that, just click ‘Save Changes.’

Saving the Meks Time Ago plugin settings

That’s it! Now, all of your post dates will have relative dates. You can view your changes on mobile, desktop, and tablet to see if everything looks right.

Here’s an example:

Example of relative dates added with the Meks Time Ago plugin

One thing we don’t like about Meks Time Ago is that, even if the post is published today or yesterday, the plugin will display the published date as ‘X mins ago’ or ‘X hours ago.’

Some people don’t mind this format, but some may also want the date to be displayed as ‘Today’ or ‘Yesterday’ instead. If that’s what you prefer, you can follow this next method.

Method 2: Using Custom Code (Customizable But Slightly Advanced)

This method involves custom code, and as we explained previously, it’s a better choice if you want to show dates as ‘Today’ or ‘Yesterday’ instead of ‘X mins ago’ or ‘X hours ago.’

But don’t get intimidated! We’re going to walk you through the process step by step. Furthermore, we will use a code snippet plugin called WPCode, which makes it safe and easy to add custom code without breaking your website.

You can learn more about the plugin in our WPCode review.

First, install and activate the WordPress plugin in your admin area.

After that, you need to go to Code Snippets » + Add Snippet. Then, select ‘Add Your Custom Code (New Snippet)’ and click the ‘+ Add Custom Snippet’ button.

Adding a new custom code snippet in WPCode

Now, give your new custom code a name. It can be something simple, like ‘Relative Date Formatted with Time.’

Also, change the Code Type to ‘PHP Snippet.’

Creating custom code to display relative dates with WPCode

Once that’s done, just copy and paste the code snippet below into the Code Preview box:

/**
 * Converts a timestamp into a human-readable relative date string.
 *
 * @param int $timestamp The timestamp to convert
 * @return string The human-readable relative date string
 */
function human_readable_relative_date( $timestamp ) {
    $time_difference = time() - $timest  // Calculate the time difference between now and the timestamp
    $seconds_in_a_day = 86400;  // Number of seconds in a day


    if ( $time_difference < 0 ) {
        return 'Date is in the future';  // Handle future dates
    } elseif ( $time_difference < $seconds_in_a_day ) {
        return 'Today at ' . date( 'H:i', $timestamp );  // Handle same-day dates
    } elseif ( $time_difference < 2 * $seconds_in_a_day ) {
        return 'Yesterday at ' . date( 'H:i', $timestamp );  // Handle one-day-old dates
    } elseif ( $time_difference < 7 * $seconds_in_a_day ) {
        $days = floor( $time_difference / $seconds_in_a_day );  // Calculate full days ago
        return $days . ($days == 1 ? ' day' : ' days') . ' ago at ' . date( 'H:i', $timestamp );  // Handle dates within the last week
    } elseif ( $time_difference < 30 * $seconds_in_a_day ) {
        $weeks = floor( $time_difference / ( 7 * $seconds_in_a_day ) );  // Calculate full weeks ago
        return $weeks . ($weeks == 1 ? ' week' : ' weeks') . ' ago at ' . date( 'H:i', $timestamp );  // Handle dates within the last month
    } elseif ( $time_difference < 365 * $seconds_in_a_day ) {
        $months = floor( $time_difference / ( 30 * $seconds_in_a_day ) );  // Calculate full months ago
        return $months . ($months == 1 ? ' month' : ' months') . ' ago at ' . date( 'H:i', $timestamp );  // Handle dates within the last year
    } else {
        $years = floor( $time_difference / ( 365 * $seconds_in_a_day ) );  // Calculate full years ago
        return $years . ($years == 1 ? ' year' : ' years') . ' ago at ' . date( 'H:i', $timestamp );  // Handle dates older than a year
    }
}


/**
 * Shortcode function to convert a given timestamp or date to a human-readable relative date string.
 *
 * @param array $atts Shortcode attributes
 * @return string The human-readable relative date string
 */
function relative_date_shortcode( $atts ) {
    $attributes = shortcode_atts(
        array(
            'timestamp' => '',  // Default value for 'timestamp' attribute
            'date' => '',       // Default value for 'date' attribute
        ),
        $atts
    );


    // If no timestamp or date attribute provided, use the post's published date
    if ( empty($attributes['timestamp']) && empty($attributes['date']) ) {
        global $post;
        if ( !is_null($post) ) {
            $attributes['timestamp'] = get_the_time('U', $post->ID);  // Get the post's timestamp
        }
    } elseif ( !empty($attributes['date']) ) {
        $attributes['timestamp'] = strtotime($attributes['date']);  // Convert 'date' attribute to timestamp
    }
    
    // Validate the timestamp
    if ( !empty($attributes['timestamp']) && is_numeric($attributes['timestamp']) ) {
        return human_readable_relative_date( $attributes['timestamp'] );  // Return the human-readable relative date
    } else {
        return 'Invalid timestamp or date';  // Return an error message if the timestamp is invalid
    }
}
add_shortcode( 'relative_date', 'relative_date_shortcode' );  // Register the shortcode

The first function, human_readable_relative_date, takes a date and changes it into a user-friendly format.

For example, it can show ‘Today at 2:30 PM’ or ‘3 days ago at 10:15 AM.’ This makes it easier for your readers to understand how old a post is.

The second function, relative_date_shortcode, creates a shortcode that you can use in WordPress. This shortcode lets you easily add relative dates to your content without changing your theme files.

By using this code, you can make your post dates more user-friendly. Readers will quickly see how recent your content is, which can make your site feel more current and engaging.

Next, scroll down to the ‘Insertion’ section. Then, choose ‘Auto Insert’ for the Insert Method and ‘Frontend Only’ for the Location.

Choosing Frontend Only as the code insertion location in WPCode

On the top right corner, change the ‘Inactive’ toggle to ‘Active’ and click on the ‘Save Snippet’ button.

With your code active, let’s see how you can enable relative dates on your WordPress blog. The process will differ based on the type of theme you’re using.

How to Add the Relative Date Format in Block Themes

If you use a block theme, then you can simply add the shortcode to your ‘Post Meta’ template part.

This template part is responsible for displaying information about your blog posts, like the author, category, and publishing date.

Pro Tip: If you’re not seeing the theme customizer menu in your WordPress admin, that means you’re probably using a block theme. Otherwise, skip to the next method.

First, go to Appearance » Editor to open the full site editor.

Selecting the Full-Site Editor from the WordPress admin panel

You will now see several options to customize your block theme.

Here, click ‘Patterns.’

Clicking the Patterns menu in the Full Site Editor

On the next page, you will see all the patterns and template parts that your theme has.

Simply select the ‘Post Meta’ option.

Editing the Post Meta template part with the full site editor

You should now see the Post Meta template part.

First, you need to delete the existing Date block so that we can replace it with our shortcode.

To do this, you can click on the Date block.

If it’s difficult to click on it, you can just click the ‘List View’ button at the top and select the ‘Date’ block. Then, click on the three-dot menu and choose ‘Delete.’

Selecting the Date block in the Post Meta template part

With the Date block deleted, go ahead and add the ‘Shortcode’ block to your Post Meta.

You can do this by clicking on the ‘+’ button anywhere on the page and dragging and dropping the Shortcode block there.

Adding a shortcode block in the full site editor

After that, type the following shortcode into the block:

[relative_date]

Once that’s done, just click ‘Save.’

Adding the relative date shortcode in the full site editor

Now, your single post template will use relative dates.

Here’s what it looks like on our demo site:

Example of a relative date made with the WPCode custom code on a block theme

How to Add the Relative Date Format in Classic Themes

The process for adding relative dates in WordPress classic themes is a bit different and more technical. This is because every classic theme has different configurations.

But bear with us. We will give you an example so that you can easily understand how to do it on your own, whether you’re using a free or premium WordPress theme.

If this is your very first time customizing your classic theme files, then we recommend doing it on a staging site or a local version of your WordPress site. This way, any unexpected errors caused by editing the code won’t affect your live website.

The first step you need to do is find the theme file that is responsible for displaying your post metadata. This can be:

  • Your single post file (usually named single.php)
  • The template part that displays your post content (something like content.php)
  • Your template tags file, which contains functions for displaying post information (commonly named template-tags.php)

As a rule of thumb, you should look for lines of code that display the post date. These lines usually call WordPress functions like the_date(), the_time(), get_the_date(), get_the_time(), get_the_modified_date(), or get_the_modified_time().

If you need help, we have a step-by-step guide on how to find which WordPress theme files to edit using a simple plugin. Alternatively, you can contact your WordPress theme developer or check out their documentation to get more assistance.

In our case, the file responsible for displaying the post date is template-tags.php. Here is the full original code the theme was using to show the exact publishing date:

if ( ! function_exists( 'twentysixteen_entry_date' ) ) :
	/**
	 * Prints HTML with date information for current post.
	 *
	 * Create your own twentysixteen_entry_date() function to override in a child theme.
	 *
	 * @since Twenty Sixteen 1.0
	 */
	function twentysixteen_entry_date() {
		$time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';

		if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) {
			$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>';
		}

		$time_string = sprintf(
			$time_string,
			esc_attr( get_the_date( 'c' ) ),
			get_the_date(),
			esc_attr( get_the_modified_date( 'c' ) ),
			get_the_modified_date()
		);

		printf(
			'<span class="posted-on"><span class="screen-reader-text">%1$s </span><a href="%2$s" rel="bookmark">%3$s</a></span>',
			/* translators: Hidden accessibility text. */
			_x( 'Posted on', 'Used before publish date.', 'twentysixteen' ),
			esc_url( get_permalink() ),
			$time_string
		);
	}
endif;

To edit the file itself, you can open the file via FTP or your WordPress hosting provider’s file manager.

If you are a Bluehost user, then you can use the file manager by logging in to your web hosting account. Then, on the dashboard, click on the ‘Websites’ tab and select ‘Settings’ for the site you’re trying to customize.

Bluehost site settings

This will open your site’s settings page.

Switch to the ‘Advanced’ tab and click on the ‘Manage’ button in the File Manager section.

Click Manage button next to the File Manager option

You should now be in the Bluehost file manager.

Since our file is called template-tags.php, we had to go to public_html » wp-content » theme-name » inc.

Opening the inc folder inside a WordPress theme using a file manager

You will now see several files to choose from.

Here, go ahead and pick template-tags.php. Right-click on the file and select ‘Edit.’

Editing the template tags classic theme file with the file manager

Now, locate the code that’s responsible for displaying the publishing date.

You can use the CTRL / Command and F keys to do this.

Finding the code responsible for displaying post dates in a WordPress theme file using the file manager

Now, you will have to edit this particular code so that it calls the human_readable_relative_date function we added using WPCode earlier.

Here’s how we replaced the original code from if ( ! function_exists( 'twentysixteen_entry_date' ) ) : to endif; :

if ( ! function_exists( 'twentysixteen_entry_date' ) ) :
	/**
	 * Prints HTML with date information for current post.
	 *
	 * Create your own twentysixteen_entry_date() function to override in a child theme.
	 *
	 * @since Twenty Sixteen 1.0
	 */
	function twentysixteen_entry_date() {
		// Get the post's published timestamp
		$published_timestamp = get_the_time('U');


		// Generate the human-readable relative date
		$relative_date = human_readable_relative_date( $published_timestamp );


		// Output the relative date
		printf(
			'<span class="posted-on"><span class="screen-reader-text">%1$s </span><a href="%2$s" rel="bookmark">%3$s</a></span>',
			/* translators: Hidden accessibility text. */
			_x( 'Posted on', 'Used before publish date.', 'twentysixteen' ),
			esc_url( get_permalink() ),
			$relative_date
		);
	}
endif;

Once you have modified the code, click on the ‘Save Changes’ button.

Saving changes made to the template tag file in the file manager

If your code doesn’t work, and you’re a complete beginner to this, then we suggest using an AI tool like OpenAI’s ChatGPT to figure out what’s wrong with your code.

You could ask a simple question like, ‘Hi, I’m trying to do X using the code below [paste your code here], but it’s not working. Can you help me figure out what’s wrong with this?’

That being said, if your code works, then this is what you should see on your single post template:

Example of a relative date on a classic theme, made with the WPCode custom code

Bonus Tips to Customize Your WordPress Blog

Other than adding relative dates to your WordPress posts, there are many other ways you can customize your blog. Here are some ideas:

We hope this article has helped you learn how to display relative dates in WordPress. You may also want to check out our expert picks of the best drag-and-drop page builders for WordPress and our ultimate guide on how to edit a WordPress website.

If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us. Here's our editorial process.

Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

The Ultimate WordPress Toolkit

Get FREE access to our toolkit - a collection of WordPress related products and resources that every professional should have!

Reader Interactions

4 CommentsLeave a Reply

  1. Dennis Muthomi

    I have used relative dates on a news (in entertainment niche) WordPress site with a similar custom code approach and it works great to increase user engagement.
    One tiny tip I’d like to add: consider using conditional logic to show absolute dates for posts older than a certain threshold (e.g. 1 year).
    This will give context to evergreen content while still using relative dates for recent posts.
    Really wanted to share that!

  2. Ziaul Hai

    I want to know how to remove relative dates. My wordpress theme shows the relative date by default. But I am not able to change that.

    • WPBeginner Support

      You could replace the relative_post_the_date with the PHP in this article depending on how you want it to display but if you reach out to your theme’s support they may have a built-in method to disable this style of date.

      Admin

  3. Sreeharsh

    Hi, I’m getting wrong time stamp using Meks Time Ago plugin in my homescreen. For a 9 hour ago post, its showing 2 weeks ago. Please help me solve it.
    Thank you.

Leave A Reply

Thanks for choosing to leave a comment. Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published. Please Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.