get_post_timestamp( int|WP_Post $post = null, string $field = ‘date’ ): int|false

Retrieves post published or modified time as a Unix timestamp.

Description

Note that this function returns a true Unix timestamp, not summed with timezone offset like older WP functions.

Parameters

$postint|WP_Postoptional
Post ID or post object. Default is global $post object.

Default:null

$fieldstringoptional
Published or modified time to use from database. Accepts 'date' or 'modified'.
Default 'date'.

Default:'date'

Return

int|false Unix timestamp on success, false on failure.

Source

function get_post_timestamp( $post = null, $field = 'date' ) {
	$datetime = get_post_datetime( $post, $field );

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

	return $datetime->getTimestamp();
}

Changelog

VersionDescription
5.3.0Introduced.

User Contributed Notes

  1. Skip to note 2 content

    How to get the published and modified date with get_post_timestamp() and then convert it into a readable format.

    <?php
    function published_modified_date() {
    
    	// UNIX published date
    	$unix_published_date = get_post_timestamp( '', 'date' );
    
    	// UNIX modified date
    	$unix_modified_date = get_post_timestamp( '', 'modified' );
    	
        // Convert from UNIX timestamp into readable date
        // Reference: https://developer.wordpress.org/reference/functions/date_i18n
    	$published_date = date_i18n( get_option( 'date_format' ), $unix_published_date );
    	$modified_date = date_i18n( get_option( 'date_format' ), $unix_modified_date );
    	
        // Convert from UNIX timestamp into full date/time (ISO)
        // Reference: https://wordpress.org/support/article/formatting-date-and-time
    	$full_published_date = date_i18n( 'c', $unix_published_date );
    	$full_modified_date = date_i18n( 'c', $unix_modified_date );
    	
        ?>
    
    	<span class="published"><time datetime="<?php echo $full_published_date; ?>"><?php echo $published_date; ?></time></span>
    	
        <?php
        // If modified date is greater than published date by 1 day 
        if ( $unix_modified_date > $unix_published_date + 86400 ) { ?>
    		<span class="modified">Modified on: <time datetime="<?php echo $full_modified_date; ?>"><?php echo $modified_date; ?></time></span>
    	    <?php
        }
    
    }

You must log in before being able to contribute a note or feedback.