The get_post_datetime() WordPress PHP function retrieves the post published or modified time as a DateTimeImmutable object instance.
Usage
get_post_datetime( $post = null, $field = 'date', $source = 'local' );
Parameters
$post
(int|WP_Post, Optional) – Post ID or post object. Default is global$post
object.$field
(string, Optional) – Published or modified time to use from database. Accepts ‘date’ or ‘modified’. Default ‘date’.$source
(string, Optional) – Local or UTC time to use from database. Accepts ‘local’ or ‘gmt’. Default ‘local’.
More information
See WordPress Developer Resources: get_post_datetime()
Examples
Get the published date of a post
This example retrieves the published date of a post with the ID 123.
$post_id = 123; $published_date = get_post_datetime( $post_id ); echo $published_date->format( 'Y-m-d H:i:s' );
Get the modified date of a post
This example retrieves the modified date of a post with the ID 123.
$post_id = 123; $modified_date = get_post_datetime( $post_id, 'modified' ); echo $modified_date->format( 'Y-m-d H:i:s' );
Get the published date in GMT
This example retrieves the published date of a post with the ID 123 in GMT.
$post_id = 123; $published_date_gmt = get_post_datetime( $post_id, 'date', 'gmt' ); echo $published_date_gmt->format( 'Y-m-d H:i:s' );
Get the published date of the current post in a loop
This example retrieves the published date of the current post in a loop.
if ( have_posts() ) { while ( have_posts() ) { the_post(); $published_date = get_post_datetime(); echo $published_date->format( 'Y-m-d H:i:s' ); } }
Get the modified date of the current post in a loop
This example retrieves the modified date of the current post in a loop.
if ( have_posts() ) { while ( have_posts() ) { the_post(); $modified_date = get_post_datetime( null, 'modified' ); echo $modified_date->format( 'Y-m-d H:i:s' ); } }