When creating a custom WordPress theme or modifying an existing one, it’s often necessary to display the publication date of a post. This helps your readers know when your content was published and can also provide a sense of context for your posts. In this blog post, we’ll show you how to get the post date in WordPress and how to format the output.
Using the_post()
To get the post date in WordPress, you can use the the_post() function. This function is used in the Loop, which is the main way WordPress displays posts on a page. Here’s a simple example of how to use the_post() to display the post date:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div> <h2><?php the_title(); ?></h2> <p>Published on <?php the_time( 'F j, Y' ); ?></p> </div> <?php endwhile; endif; ?>
In this example, we use the the_time() function to display the post’s publish date. The parameter passed to the_time() is a format string that determines how the date will be displayed. In this case, we’re using ‘F j, Y’ to display the date in the format “Month Day, Year” (e.g., January 1, 2020).
Using get_the_date()
Another way to get the post date in WordPress is to use the get_the_date() function. This function retrieves the post date without displaying it directly. This can be useful if you want to store the date in a variable for further processing or formatting:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div> <h2><?php the_title(); ?></h2> <?php $date = get_the_date( 'F j, Y' ); ?> <p>Published on <?php echo $date; ?></p> </div> <?php endwhile; endif; ?>
Just like with the_time(), you can pass a format string to get_the_date() to control how the date will be displayed.
Formatting the Post Date
You may want to display the post date in a different format or style. The good news is that both the_time() and get_the_date() support PHP’s date format characters, which allows you to customize the output to your liking. Here are a few examples of different formatting options:
- the_time(‘F j, Y’) – Month Day, Year (e.g., January 1, 2020)
- the_time(‘m/d/Y’) – Month/Day/Year (e.g., 01/01/2020)
- the_time(‘Y-m-d’) – Year-Month-Day (e.g., 2020-01-01)
- the_time(‘g:i a’) – Hour:Minutes AM/PM (e.g., 12:30 pm)
You can also combine these format strings to display the date and time together:
<?php the_time( 'F j, Y g:i a' ); ?> // Output: January 1, 2020 12:30 pm
Conclusion
Displaying the post date in WordPress is easy thanks to the built-in functions like the_time() and get_the_date(). By customizing the format string, you can display the date and time in any way that suits your theme’s design. Remember to always make use of these functions within the Loop, as they are designed to work with the current post in the loop.