Wordpress - How to get the post publish date outside the loop?
get_the_date
must be used inside the Loop. For outside the loop use get_the_time
.
$posts = get_posts(array('numberposts'=>-1)); //Get all published posts
foreach ($posts as $post){
echo get_the_time('Y-m-d', $post->ID); //Echos date in Y-m-d format.
}
Consider replacing 'Y-m-d'
in this example with get_option('date_format')
as this will display the date as per your date format setting in wp-admin.
You can use get_post() or get_post_field() for this, both work outside the loop.
$post_object = get_post($id);
$post_date = date( 'F jS, Y', strtotime( $post_object->post_date ) );
A full list of values returned by get_post:
WP_Post Object
(
[ID] =>
[post_author] =>
[post_date] =>
[post_date_gmt] =>
[post_content] =>
[post_title] =>
[post_excerpt] =>
[post_status] =>
[comment_status] =>
[ping_status] =>
[post_password] =>
[post_name] =>
[to_ping] =>
[pinged] =>
[post_modified] =>
[post_modified_gmt] =>
[post_content_filtered] =>
[post_parent] =>
[guid] =>
[menu_order] =>
[post_type] =>
[post_mime_type] =>
[comment_count] =>
[filter] =>
)