WordPress at a glance

get_post_time() WP 2.0.0

Gets the time of the current post creation in the specified format. You can specify a return format (the default is Unix format). Must be used in WordPress loop.

The function gets a result for processing in php, and does not display it to the screen. Use the_time() to display the result.

Works based on: mysql2date()
Basis of: get_the_time()
Hooks from the function
Return

String/Int/false. Formatted date string or Unix timestamp if $format is 'U' or 'G'. False on failure.

Usage

get_post_time( $format, $gmt, $post, $translate );
$format(string)
Format to use for retrieving the time the post was written. Either 'G', 'U', or PHP date format.
Default: 'U'
$gmt(true/false)
Whether to retrieve the GMT time.
Default: false
$post(int/WP_Post)
WP_Post object or ID.
Default: global $post object
$translate(true/false)
Whether to translate the time string.
Default: false

Examples

#1 Get the timestamp of the post

To get a Unix timestamp of a post adjusted for the GMT time zone (the second parameter), you can use the function like so:

$gmt_timestamp = get_post_time( 'U', true );
echo $gmt_timestamp; //> 1521992006

Changelog

Since 2.0.0 Introduced.

Code of get_post_time() WP 5.5.3

<?php
function get_post_time( $format = 'U', $gmt = false, $post = null, $translate = false ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return false;
	}

	$source   = ( $gmt ) ? 'gmt' : 'local';
	$datetime = get_post_datetime( $post, 'date', $source );

	if ( false === $datetime ) {
		return false;
	}

	if ( 'U' === $format || 'G' === $format ) {
		$time = $datetime->getTimestamp();

		// Returns a sum of timestamp with timezone offset. Ideally should never be used.
		if ( ! $gmt ) {
			$time += $datetime->getOffset();
		}
	} elseif ( $translate ) {
		$time = wp_date( $format, $datetime->getTimestamp(), $gmt ? new DateTimeZone( 'UTC' ) : null );
	} else {
		if ( $gmt ) {
			$datetime = $datetime->setTimezone( new DateTimeZone( 'UTC' ) );
		}

		$time = $datetime->format( $format );
	}

	/**
	 * Filters the localized time a post was written.
	 *
	 * @since 2.6.0
	 *
	 * @param string $time   The formatted time.
	 * @param string $format Format to use for retrieving the time the post was written.
	 *                       Accepts 'G', 'U', or PHP date format. Default 'U'.
	 * @param bool   $gmt    Whether to retrieve the GMT time. Default false.
	 */
	return apply_filters( 'get_post_time', $time, $format, $gmt );
}

From tag: date time

More from category: Posts, pages...

More from Template Tags: Posts, Pages, ...

vladlu 100vlad.lu
Editors: Kama 100
No comments
    Log In