Retrieving Publish Date of a Post in WordPress is an easy task to do. We'll try retrieving post attributes using a specific Post ID or current queried post id to show you how to work with Post Dates in WordPress using the get_the_date function.
Retrieving publish date of a WordPress post using get_the_date
function
get_the_date
function is introduced by WordPress to let developers get publish date of a specific post ID or current post inside a loop.
This function receives 2 optional arguments:
- Date format: you can specify the format, using PHP date formats
- Post ID or WP_Post object: retrieving title of specific post
get_the_date
syntax in WordPress:
get_the_date(string $format = '', int|WP_Post $post)
Keep reading for examples…
Get specific post publish date in WordPress using post ID
In this example we’ll try to print publish date of a post with an ID equal to 1:
$postId = 1;
echo get_the_time('Y-m-d', $postId);
Get publish date of current post in WordPress
If you are interested in printing publish date of the current post (inside a loop or single.php
file), use get_the_time
function with no post id.
Example of using this function inside a loop:
$posts = new WP_Query(array('post_type' => 'post')); //retrieve posts
if($posts->have_posts() ) {
while($posts->have_posts() ) {
$posts->the_post();
echo get_the_time('Y-m-d'); //Echos date in Y-m-d format.
}
}
$posts->the_post()
will change the global $post
object in WordPress. this object is the reference for the get_the_time
function when you do not specify the ID.
Remember to reset the global $post
object back to WordPress default after changing it. You only need to use the wp_reset_postdata
function to reset it back after custom loops.
If you are a hard-working student, keep reading. you can read How to set publishing date and time for a WordPress post Programmatically? in my tutorial archive.
A good start point for my new visitors is How to create a Hello World plugin for WordPress in 3 Steps article which contains good tips for those who want to use standard codes and methods.
written by Mehdi Nazari about in WordPress WordPress Functions WordPress Plugin Development WordPress Theme Development
What do you think about "How to Get WordPress Post Date Using PHP (+2 Examples)"?