Working with DateTime in WordPress: A Practical Guide
Handling dates and times in WordPress can be tricky, especially when you want to format, compare, or manipulate them. Fortunately, WordPress provides a set of functions to help developers easily work with DateTime objects. These tools ensure that you’re managing time efficiently, respecting time zones, and formatting dates in the way that suits your site.
Using DateTime Objects in WordPress
1. Getting Current Date and Time
To get the current date and time, WordPress provides the current_time() function. This can return the time in a variety of formats:
// Current time in MySQL format e.g. 2024-11-22 10:41:48
echo current_time('Y-m-d H:i:s');
// GMT time e.g. 2024-11-22 11:41:48
echo current_time('mysql', true);
PHPYou can also retrieve the current time as an object using the site’s timezone with the current_datetime() function:
$current_date_time = current_datetime();
echo $current_date_time->format('Y-m-d');
PHP2. Working with Post Dates
Each post in WordPress has its own timestamp. You can retrieve it with get_post_datetime(),This function returns a DateTime object, which you can format as you wish.
$post_date = get_post_datetime($post_id);
if ($post_date) {
echo $post_date->format('Y-m-d');
}
PHP3. Converting Strings to DateTime Objects
If you’re dealing with date strings (e.g., from a database or form), you can convert them into DateTime objects:
$meta_date = '13/01/2024';
$datetime = DateTime::createFromFormat('d/m/Y', $meta_date);
echo $datetime->format('Y-m-d');
PHP4. Calculating Differences Between Dates
To calculate the difference between two DateTime objects, you can use the diff()
method. This method is useful for calculating things like how much time has passed between events or how long ago something happened.
$datetime1 = DateTime::createFromFormat('d/m/Y', '01/01/2023');
$datetime2 = DateTime::createFromFormat('d/m/Y', '01/01/2024');
$diff = $datetime1->diff($datetime2);
echo "Difference: {$diff->days} days";
PHP5. Modifying DateTime Objects
You can modify DateTime objects by using the modify()
method. This allows you to add or subtract time:
$datetime = DateTime::createFromFormat('d/m/Y', '10/02/2024');
// Adds three days and displays the new date
$datetime->modify('+3 day');
echo $datetime->format('d M Y'); // 13 Feb 2024
PHPYou can chain modifications:
$datetime->modify('+1 month -2 days');
echo $datetime->format('d M Y');
PHPPractical Examples
1. Scheduling a Custom Event
Using current_datetime()
in WordPress is a simple way to schedule tasks like custom events or reminders. It ensures accurate time handling and works seamlessly with WordPress’s scheduling tools. Here’s an example to show how to use it.
// Get current time
$current_time = current_datetime();
$current_time->modify('+2 days');
// Schedule a custom event
wp_schedule_single_event($current_time->getTimestamp(), 'my_custom_event');
PHP2. Custom Display of Post Dates
You can use get_post_datetime()
to dynamically fetch and format post dates, customizing how dates appear on your site.
$post_date = get_post_datetime($post->ID);
echo "This post was published on " . $post_date->format('l, F j, Y');
PHP3. Show Posts Older Than a Certain Date
To highlight posts older than a specific date, you can combine WordPress’s WP_Query
with the DateTime
class. First, calculate the date threshold dynamically using DateTime::modify('-1 year')
.Then pass this date in your query arguments to fetch posts published earlier.
$one_year_ago = current_datetime()->modify('-1 year')->format('Y-m-d');
$query = new WP_Query([
'date_query' => [
'before' => $one_year_ago,
],
'posts_per_page' => 5,
]);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
echo get_the_title() . '<br>';
}
}
wp_reset_postdata();
PHP4. Calculate Time Since Post Published
To show how long ago a post was published, use the DateTime
class with WordPress functions like get_the_date()
. Calculate the time difference between the post’s publish date and the current date, then format the result as “2 days ago” or “3 weeks ago.”
$post_date = get_post_datetime($post->ID);
$now = current_datetime();
$diff = $post_date->diff($now);
echo "This post was published {$diff->days} days ago.";
PHP5. Expire a Custom Meta Field
Automatically remove a meta value when it reaches its expiration date:
$expiry_date = get_post_meta($post->ID, 'expiry_date', true);
$expiry_datetime = DateTime::createFromFormat('Y-m-d', $expiry_date);
if ($expiry_datetime < current_datetime()) {
delete_post_meta($post->ID, 'expiry_date');
echo "Meta expired and removed!";
}
PHP6. Customizing Time Zones
Adapt time zone adjustments for multi-regional sites:
$user_timezone = 'America/New_York';
$now = new DateTime('now', new DateTimeZone($user_timezone));
echo "Current time in $user_timezone: " . $now->format('Y-m-d H:i:s');
PHP7. Display Events Starting Soon
List events starting in the next 7 days:
$today = current_datetime()->format('Y-m-d');
$next_week = current_datetime()->modify('+7 days')->format('Y-m-d');
$args = [
'meta_query' => [
'key' => 'event_start_date',
'value' => [$today, $next_week],
'compare' => 'BETWEEN',
'type' => 'DATE',
],
];
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
echo get_the_title() . " starts on "
. get_post_meta(get_the_ID(), 'event_start_date', true) . "<br>";
}
}
wp_reset_postdata();
PHPConclusion
By integrating DateTime with WordPress functions, you can efficiently handle dates and times for real world tasks, such as event scheduling, post filtering, and time calculations. These examples showcase practical, easy to implement scenarios that enhance functionality and improve user experience.
Photo by Estée Janssens on Unsplash