Function and usage of current_time() in wordpress


Answers ( 1 )


    The current_time() function in WordPress is a versatile tool for retrieving the current time, with different formats based on the specified type. Here's a detailed explanation and sample usage:

    Function Signature:

    current_time( string $type, int|bool $gmt ): int|string


    • The function current_time() fetches the current time, with the format dictated by the $type parameter.
    • Depending on $type, the time is formatted in various ways:
      • 'mysql': Returns the time in the format suitable for a MySQL DATETIME field.
      • 'timestamp' or 'U': Returns the current Unix timestamp. If $gmt is truthy, it will be GMT time; otherwise, it's adjusted for the site's GMT offset.
      • Any other string is treated as a PHP date format string, like 'Y-m-d'.
    • The $gmt parameter controls whether the time is in GMT or adjusted for the site's timezone. A truthy value (true, non-zero number) means GMT is used.


    • $type (string, required): Specifies the type of time to retrieve. It can be 'mysql', 'timestamp', 'U', or any PHP date format string (e.g., 'Y-m-d').
    • $gmt (int|bool, optional): Determines whether to use GMT timezone (true for GMT, false or omitted for local time). Default is false.


    • Returns an integer if $type is 'timestamp' or 'U', and a string for all other types.

    Sample Usage:

    1. MySQL DATETIME Format:

      $current_mysql_time = current_time('mysql');
      // Returns the current time in MySQL DATETIME format
    2. Current Unix Timestamp:

      $current_timestamp = current_time('timestamp');
      // Returns the current Unix timestamp adjusted for site's timezone
    3. GMT Unix Timestamp:

      $gmt_timestamp = current_time('timestamp', true);
      // Returns the current Unix timestamp in GMT
    4. Custom PHP Date Format:

      $formatted_date = current_time('Y-m-d');
      // Returns the current date in 'YYYY-MM-DD' format
    5. Using GMT with Custom Format:

      $gmt_formatted_date = current_time('Y-m-d H:i:s', true);
      // Returns the current date and time in GMT in 'YYYY-MM-DD HH:MM:SS' format

    This function is especially useful for developers who need to display or manipulate dates and times in various formats within a WordPress environment.

Leave an answer