Using WordPress ‘get_post_time’ PHP filter

The get_post_time WordPress PHP filter allows you to modify the localized time a post was written.

Usage

add_filter('get_post_time', 'your_custom_function', 10, 3);
function your_custom_function($time, $format, $gmt) {
  // your custom code here
  return $time;
}

Parameters

  • $time (string|int): Formatted date string or Unix timestamp if $format is ‘U’ or ‘G’.
  • $format (string): Format to use for retrieving the time the post was written. Accepts ‘G’, ‘U’, or PHP date format.
  • $gmt (bool): Whether to retrieve the GMT time.

More information

See WordPress Developer Resources: get_post_time

Examples

Change time format

Change the time format to display hours, minutes, and seconds.

add_filter('get_post_time', 'change_time_format', 10, 3);
function change_time_format($time, $format, $gmt) {
  $format = 'H:i:s';
  $time = get_post_time($format, $gmt);
  return $time;
}

Add 2 hours to post time

Modify the post time by adding 2 hours to the original time.

add_filter('get_post_time', 'add_two_hours', 10, 3);
function add_two_hours($time, $format, $gmt) {
  $timestamp = strtotime($time) + (2 * 60 * 60);
  return date($format, $timestamp);
}

Convert post time to a different timezone

Convert the post time from GMT to the specified timezone.

add_filter('get_post_time', 'convert_timezone', 10, 3);
function convert_timezone($time, $format, $gmt) {
  $datetime = new DateTime($time, new DateTimeZone('GMT'));
  $datetime->setTimezone(new DateTimeZone('America/New_York'));
  return $datetime->format($format);
}

Display relative time (e.g., “5 minutes ago”)

Show the post time as a relative time from the current time.

add_filter('get_post_time', 'display_relative_time', 10, 3);
function display_relative_time($time, $format, $gmt) {
  $current_time = current_time('timestamp', $gmt);
  $post_time = strtotime($time);
  $time_difference = $current_time - $post_time;
  return human_time_diff($post_time, $current_time) . ' ago';
}

Display post time only on specific days

Only display the post time on posts published on Monday.

add_filter('get_post_time', 'display_time_on_monday', 10, 3);
function display_time_on_monday($time, $format, $gmt) {
  $post_day = date('l', strtotime($time));
  if ($post_day == 'Monday') {
    return $time;
  } else {
    return '';
  }
}