How to Display Relative Dates in WordPress (2 Methods)

How to Display Relative Dates in WordPress (2 Methods)
Relative dates, also known as “time ago” or “human-readable dates,” are a user-friendly way to display dates in WordPress. Instead of showing the exact date and time, like “November 8, 2024, at 3:00 PM,” a relative date might display “2 hours ago” or “Yesterday.” This offers a more immediate and intuitive understanding of the freshness of the content. Using relative dates can significantly improve the user experience, especially for news sites, blogs with frequent updates, and social media integrations.
This article will explore two practical methods for implementing relative dates in your WordPress website. The first method involves using a plugin, which is the easiest and most convenient option for beginners. The second method focuses on using custom code, providing greater flexibility and control for more advanced users who prefer a more hands-on approach.
Method 1: Using a WordPress Plugin
This method is the simplest and most recommended for users who aren’t comfortable with directly modifying their theme files. Several excellent plugins are available in the WordPress repository that handle the complexity of calculating and displaying relative dates.
Selecting a Plugin
Before diving in, it’s important to choose a suitable plugin. Here are a few popular and reliable options:
- WP Last Modified Info: This plugin allows you to display the last modified date in a relative format. It also offers control over placement and styling.
- PublishPress Revisions: While primarily designed for managing revisions, this plugin also provides options to display relative dates for posts and pages.
- Relative Time: A dedicated plugin specifically designed for displaying relative timestamps.
For this tutorial, we will use the “WP Last Modified Info” plugin for demonstration purposes. The general principles are applicable to other similar plugins.
Installing and Activating the Plugin
1. Navigate to the WordPress Plugin Directory: From your WordPress dashboard, go to “Plugins” -> “Add New.”
2. Search for the Plugin: In the search bar, type “WP Last Modified Info.”
3. Install the Plugin: Locate the plugin in the search results and click “Install Now.”
4. Activate the Plugin: Once the installation is complete, click the “Activate” button.
Configuring the Plugin
Most relative date plugins offer various customization options. Let’s explore some common configuration settings for “WP Last Modified Info.”
1. Access Plugin Settings: Go to “Settings” -> “WP Last Modified Info.” You should find a configuration panel with different options.
2. Enable Relative Dates: Look for an option to enable relative dates or “time ago” format. The specific wording may vary depending on the plugin.
3. Choose Date Location: Configure where you want the date to appear (e.g., before content, after content, custom location).
4. Customize the Format: Many plugins allow you to customize the format of the relative date string. For example, you might be able to choose between “X minutes ago,” “X hours ago,” “Yesterday,” and so on. Some plugins also allow for date formatting strings to control how the dates are displayed.
5. Target Specific Post Types: Most plugins allow you to specify which post types (posts, pages, custom post types) the relative date should be displayed on.
Testing the Plugin
After configuring the plugin, it’s crucial to test it to ensure it’s working as expected.
1. Visit Your Website: Navigate to a post or page where the plugin is configured to display the relative date.
2. Verify the Display: Check if the date is displayed correctly in the relative format. It should reflect the time elapsed since the content was last modified.
3. Adjust Settings (If Necessary): If the date isn’t displaying as you’d like, revisit the plugin settings and adjust the configuration accordingly.
Pros and Cons of Using a Plugin
Pros:
- Easy to install and configure
- No coding required
- Often includes various customization options
- Suitable for beginners and non-technical users
Cons:
- Can potentially add bloat to your website (though well-coded plugins minimize this)
- Limited control compared to custom code
- Reliance on a third-party plugin
Method 2: Using Custom Code
For developers or those comfortable with coding, implementing relative dates using custom code offers greater flexibility and control. This method involves modifying your theme’s template files or using a custom function within your `functions.php` file (or a custom plugin).
Creating a Custom Function
The core of this method is a function that calculates the time difference between a given date and the current time and then returns a human-readable string. Here’s a sample function:
“`php
function time_ago($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
‘y’ => ‘year’,
‘m’ => ‘month’,
‘w’ => ‘week’,
‘d’ => ‘day’,
‘h’ => ‘hour’,
‘i’ => ‘minute’,
‘s’ => ‘second’,
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ‘ ‘ . $v . ($diff->$k > 1 ? ‘s’ : ”);
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(‘, ‘, $string) . ‘ ago’ : ‘just now’;
}
“`
Explanation of the code:
- The function `time_ago` takes a `$datetime` string as input.
- It creates `DateTime` objects for both the current time (`$now`) and the provided `$datetime` (`$ago`).
- It calculates the difference between the two dates using `$now->diff($ago)`.
- The code then formats the difference into a human-readable string (e.g., “2 hours ago,” “1 day ago”).
- The function returns the formatted string.
Adding the Function to Your Theme
There are two primary ways to add this function to your WordPress theme:
1. Using `functions.php`: This is the most common method. Open your theme’s `functions.php` file (or the `functions.php` file of your child theme if you’re using one). Add the code snippet above to the end of the file. Important: Always use a child theme to modify theme files to prevent losing changes during theme updates.
2. Creating a Custom Plugin: For a more organized approach, especially if you have multiple custom functions, you can create a simple plugin to house your code. This keeps your theme’s `functions.php` file cleaner and makes your custom functions portable across different themes.
Displaying the Relative Date in Your Theme
Once you’ve added the function, you need to call it within your theme’s template files to display the relative date. Identify the template file responsible for displaying the post date (e.g., `single.php`, `index.php`, `archive.php`).
Example:
Let’s say you want to display the relative date in your `single.php` file. Find the line of code that displays the original date, which might look something like this:
“`php
“`
This code calls the `time_ago` function, passing the post’s date as an argument. The function then returns the relative date string, which is displayed within the `
Customizing the Output
You can further customize the output of the `time_ago` function to suit your specific needs.
- Adjusting the Thresholds: Modify the code to change the thresholds at which different time units are displayed (e.g., show “Yesterday” instead of “1 day ago”).
- Adding Custom Text: Include custom text before or after the relative date string (e.g., “Published X hours ago”).
- Styling the Output: Use CSS to style the appearance of the relative date.
Pros and Cons of Using Custom Code
Pros:
- Greater flexibility and control over the implementation
- No reliance on third-party plugins
- Potentially more lightweight than using a plugin (if coded efficiently)
- Opportunity to learn more about WordPress development
Cons:
- Requires coding knowledge
- Can be more time-consuming to implement
- Potential for errors if not coded carefully
- Maintenance responsibility lies solely with you
Important Considerations
Regardless of the method you choose, consider these important factors:
- Performance: While relative dates generally don’t have a significant impact on performance, be mindful of the complexity of the calculation and the frequency with which it’s executed. Optimize your code if necessary.
- Caching: If you’re using a caching plugin, ensure that it’s configured to properly cache the relative dates. Otherwise, the dates might not update correctly.
- Time Zones: Be aware of time zone differences. Make sure your WordPress settings are configured with the correct time zone to ensure accurate relative date calculations.
- Localization: If your website is multilingual, ensure that your chosen method supports localization of the relative date strings. Plugins often provide localization options. If you’re using custom code, you might need to use WordPress’s internationalization functions (i18n).
- Accessibility: Ensure that your implementation is accessible to users with disabilities. Use appropriate HTML tags and ARIA attributes to provide context and meaning to the relative dates. Using the <time> element with a proper datetime attribute as shown in the examples is a good first step.
Conclusion
Implementing relative dates in WordPress can significantly enhance the user experience by providing a more intuitive understanding of the freshness of content. While plugins offer a convenient and easy-to-use solution, custom code provides greater flexibility and control. Choose the method that best suits your technical skills and project requirements, keeping in mind the considerations outlined above. By implementing relative dates effectively, you can create a more engaging and user-friendly website.