Using WordPress ‘date_i18n’ PHP filter

The date_i18n WordPress PHP filter allows you to change the formatted date based on the locale.

Usage

add_filter('date_i18n', 'your_custom_function', 10, 4);
function your_custom_function($date, $format, $timestamp, $gmt) {
  // your custom code here
  return $date;
}

Parameters

  • $date (string) – Formatted date string.
  • $format (string) – Format to display the date.
  • $timestamp (int) – A sum of Unix timestamp and timezone offset in seconds. Might be without offset if input omitted timestamp but requested GMT.
  • $gmt (bool) – Whether to use GMT timezone. Only applies if timestamp was not provided. Default false.

More information

See WordPress Developer Resources: date_i18n

Examples

Change date format for a specific locale

Change the date format for the German locale.

add_filter('date_i18n', 'change_date_format_german_locale', 10, 4);
function change_date_format_german_locale($date, $format, $timestamp, $gmt) {
  if (get_locale() == 'de_DE') {
    $format = 'd.m.Y';
    $date = date_i18n($format, $timestamp, $gmt);
  }
  return $date;
}

Display dates in uppercase

Transform the dates to uppercase.

add_filter('date_i18n', 'uppercase_dates', 10, 1);
function uppercase_dates($date) {
  return strtoupper($date);
}

Add custom prefix to dates

Add a custom prefix to dates.

add_filter('date_i18n', 'add_custom_prefix_to_dates', 10, 1);
function add_custom_prefix_to_dates($date) {
  return 'Date: ' . $date;
}

Change date format based on post type

Change the date format based on the post type.

add_filter('date_i18n', 'change_date_format_based_on_post_type', 10, 4);
function change_date_format_based_on_post_type($date, $format, $timestamp, $gmt) {
  $post_type = get_post_type();
  if ($post_type == 'event') {
    $format = 'F j, Y';
    $date = date_i18n($format, $timestamp, $gmt);
  }
  return $date;
}

Display dates in a custom format for a specific category

Display dates in a custom format for posts in the ‘news’ category.

add_filter('date_i18n', 'custom_date_format_for_news_category', 10, 4);
function custom_date_format_for_news_category($date, $format, $timestamp, $gmt) {
  if (in_category('news')) {
    $format = 'l, F j, Y';
    $date = date_i18n($format, $timestamp, $gmt);
  }
  return $date;
}