Using WordPress ‘get_the_time’ PHP filter

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

Usage

add_filter('get_the_time', 'your_custom_function', 10, 3);
function your_custom_function($the_time, $format, $post) {
  // your custom code here
  return $the_time;
}

Parameters

  • $the_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.
  • $post (WP_Post) – Post object.

More information

See WordPress Developer Resources: get_the_time

Examples

Add custom time format

Change the time format for a specific post type.

add_filter('get_the_time', 'custom_time_format', 10, 3);
function custom_time_format($the_time, $format, $post) {
  if ($post->post_type == 'custom_post_type') {
    $the_time = get_the_time('g:i A', $post);
  }
  return $the_time;
}

Add time ago

Show the time ago instead of the post time.

add_filter('get_the_time', 'time_ago_format', 10, 3);
function time_ago_format($the_time, $format, $post) {
  return human_time_diff(get_post_time('U', true, $post)) . ' ago';
}

Add a timezone offset

Add a timezone offset to the post time.

add_filter('get_the_time', 'timezone_offset', 10, 3);
function timezone_offset($the_time, $format, $post) {
  $timezone_offset = 1 * 60 * 60; // 1 hour
  $post_time = strtotime($the_time) + $timezone_offset;
  return date($format, $post_time);
}

Change time format on specific category

Change the time format for posts in a specific category.

add_filter('get_the_time', 'category_time_format', 10, 3);
function category_time_format($the_time, $format, $post) {
  if (has_category('custom-category', $post)) {
    $the_time = get_the_time('g:i A', $post);
  }
  return $the_time;
}

Modify time format for logged-in users

Show a different time format for logged-in users.

add_filter('get_the_time', 'loggedin_users_time_format', 10, 3);
function loggedin_users_time_format($the_time, $format, $post) {
  if (is_user_logged_in()) {
    $the_time = get_the_time('g:i A', $post);
  }
  return $the_time;
}