get_post_datetime()

最后更新于:2021-11-26 22:29:59

get_post_datetime( int|GC_Post$post=null, string$field=’date’, string$source=’local’)

Retrieve post published or modified time as a DateTimeImmutable object instance.

参数

$post

(int|GC_Post) (Optional) GC_Post object or ID. Default is global $post object.

Default value: null

$field

(string) (Optional) Published or modified time to use from database. Accepts ‘date’ or ‘modified’.

Default value: ‘date’

$source

(string) (Optional) Local or UTC time to use from database. Accepts ‘local’ or ‘gmt’.

Default value: ‘local’

响应

(DateTimeImmutable|false) Time object on success, false on failure.

源文件

文件: gc-includes/general-template.php

function get_post_datetime( $post = null, $field = 'date', $source = 'local' ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return false;
	}

	$gc_timezone = gc_timezone();

	if ( 'gmt' === $source ) {
		$time     = ( 'modified' === $field ) ? $post->post_modified_gmt : $post->post_date_gmt;
		$timezone = new DateTimeZone( 'UTC' );
	} else {
		$time     = ( 'modified' === $field ) ? $post->post_modified : $post->post_date;
		$timezone = $gc_timezone;
	}

	if ( empty( $time ) || '0000-00-00 00:00:00' === $time ) {
		return false;
	}

	$datetime = date_create_immutable_from_format( 'Y-m-d H:i:s', $time, $timezone );

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

	return $datetime->setTimezone( $gc_timezone );
}