Using get_the_time to get the publish time of current post in WordPress

The get_the_time function in WordPress is a template tag that retrieves the time at which the current post was written. This function is usually used in The Loop, the main control structure used in WordPress to process posts.

One of the primary uses of the get_the_time function is to display the time of each post in a WordPress site. This can be useful for visitors who want to know when a particular post was last updated. It can also be beneficial for website administrators for tracking and organizing content updates.

It is worth noting that the get_the_time function returns the time in the format specified in the WordPress settings, unless a specific format is provided when the function is called.

Parameters Accepted by get_the_time Function

The get_the_time function in WordPress accepts two parameters which are both optional:

  • $format (string): The default value for this parameter is an empty string. It defines the format to be used when retrieving the time the post was written. It accepts ‘G’, ‘U’, or PHP date format. If not specified, it defaults to the ‘time_format’ option.
  • $post (intWP_Post): This parameter can be a Post ID or a post object. If not specified, it defaults to the global $post object.

Return Value of get_the_time Function

The get_the_time function returns a string, integer, or false. It returns a formatted date string or a Unix timestamp if the $format is ‘U’ or ‘G’. If the function fails, it returns false.

If the function does not accept any parameters, it will simply return the time the post was written in the default ‘time_format’ option.

Examples

How to display the time a post was published

<?php
echo '<p>This post was published at: ' . get_the_time('g:i a') . '</p>';
?>

This code snippet displays the time a post was published in the format of hours:minutes am/pm. The get_the_time('g:i a') function is used to get the time the current post was published.

How to use get_the_time function inside a loop

<?php
if ( have_posts() ) {
 while ( have_posts() ) {
 the_post();
 echo '<p>This post was published at: ' . get_the_time('g:i a') . '</p>';
 }
}
?>

This code snippet is used inside the WordPress loop to display the time each post was published. The get_the_time('g:i a') function is used to get the time each post was published. The time is displayed in the format of hours:minutes am/pm.

Conclusion

The get_the_time function in WordPress is a key tool that retrieves the time at which a specific post was written. This function is often utilized to display the time of each post in a variety of formats, depending on the specific needs of the website. By leveraging the flexibility of the get_the_time function, developers can customize how and where the post time is displayed, thereby enhancing the overall user experience and the informational value of the website content.

Related WordPress Functions