Using WordPress ‘current_time()’ PHP function

The current_time() WordPress PHP function retrieves the current time based on the specified type.

Usage

$current_time = current_time('mysql');

In this example, the function will return the current time in the format for MySQL DATETIME field.

Parameters

  • $type (string) (Required): Type of time to retrieve. Accepts ‘mysql’, ‘timestamp’, ‘U’, or PHP date format string (e.g. ‘Y-m-d’).
  • $gmt (int|bool) (Optional): Whether to use GMT timezone. Default is false.

More information

See WordPress Developer Resources: current_time()

Please note that since WordPress 5.3, it’s not recommended to retrieve time as WP timestamp: current_time('timestamp'). The recommended way is to use Unix timestamp or DateTimeImmutable object: time() or current_datetime().

The current_time() function can return a warning with PHP version 7.0.0 and later, because the ‘split’ function was removed. An alternative is to use the ‘preg_split()’ function.

Examples

Example 1

This code gets the current time in MySQL format:

$mysql_time = current_time('mysql');
// Output: 2023-05-10 15:42:30

The $mysql_time variable now holds the current time in the format for MySQL DATETIME field.

Example 2

This code gets the current time in GMT:

$gmt_time = current_time('mysql', 1);
// Output: 2023-05-10 20:42:30

The $gmt_time variable now holds the current time in GMT.

Example 3

This code gets the current time as a timestamp:

$timestamp = current_time('timestamp');
// Output: 1652200950

The $timestamp variable now holds the current timestamp.

Example 4

This code splits the current time into year, month, day, hour, minute, and second:

$blogtime = current_time('mysql');
list($today_year, $today_month, $today_day, $hour, $minute, $second) = preg_split('/([^0-9])/', $blogtime);
// Output: $today_year = 2023, $today_month = 05, $today_day = 10, $hour = 15, $minute = 42, $second = 30

The variables $today_year, $today_month, $today_day, $hour, $minute, and $second now hold the respective values of the current time.

Example 5

This code gets the current Unix timestamp adjusted for the site’s timezone:

$local_time = current_datetime();
$current_time = $local_time->getTimestamp() + $local_time->getOffset();
// Output: 1652200950

The $current_time variable now holds the current Unix timestamp adjusted for the site’s timezone.