Display the Last Updated Date

This code snippet allows you to display the last updated date of a post in WordPress. It checks if the post has been modified within the last 24 hours before displaying the updated date.

The code retrieves the post’s published time ($u_time) and modified time ($u_modified_time) using the get_the_time and get_the_modified_time functions, respectively.

If the modified time is greater than or equal to the published time plus 86400 seconds (which represents 24 hours), it means the post has been modified within the last 24 hours. In this case, the code generates an HTML paragraph (<p>) with the class “last-updated” and constructs the text using the sprintf function. The placeholders %1$s and %2$s are replaced with the updated date and time, respectively.

Finally, the generated HTML is echoed using the wp_kses_post function to ensure any HTML tags within the generated content are properly sanitized.

To display the last updated date, add this code within the WordPress loop in your theme files, such as single.php or content.php.

PHP
$u_time          = get_the_time( 'U' );
$u_modified_time = get_the_modified_time( 'U' );
// Only display modified date if 24hrs have passed since the post was published.
if ( $u_modified_time >= $u_time + 86400 ) {
	$updated_date = get_the_modified_time( 'F jS, Y' );
	$updated_time = get_the_modified_time( 'h:i a' );
	$updated = '<p class="last-updated">';
	$updated .= sprintf(
	// Translators: Placeholders get replaced with the date and time when the post was modified.
		esc_html__( 'Last updated on %1$s at %2$s' ),
		$updated_date,
		$updated_time
	);
	$updated .= '</p>';
	echo wp_kses_post( $updated );
}