The function get_the_time
is only designed to work either in the main WordPress loop or a custom loop using WP_Query
, so the way you are using it won’t work correctly. The following is the right way to use it, using a custom WP_Query
loop:
<?php
// Get years that have posts
$years = $wpdb->get_results( "SELECT DISTINCT YEAR(post_date) AS year FROM $wpdb->posts WHERE post_type="post" AND post_status="publish" ORDER BY year ASC;" );
// For each year, do the following
foreach ( $years as $year ) {
// Get all posts for the year. Using WP_Query instead of custom mySQL
$posts_this_year = new WP_Query( array(
'post_type' => 'post',
'post_status' => 'publish',
'year' => $year->year
) );
// Display the year as a header
echo '<h1>' . $year->year . '</h1>';
// Start an unorder list
echo '<ul class="posts-in-year">';
// As long as you have posts for that year, do the following. Using the Loop. get_the_date now works
while ( $posts_this_year->have_posts() ) {
//Makes current post available to template tag functions like get_the_time
$posts_this_year->the_post();
// Display the title as a hyperlinked list item
echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a>' . ' ' . '—' . ' ' . get_the_time('F j') . '</li>';
}
//Reset post data. Important to do this so not to mess with main loop
wp_reset_postdata();
// End the unordered list
echo '</ul>';
}
?>
The Loop, which I was referring to earlier, is when you use WP_Query
to iterate through the posts for you. When you do it that way, functions like get_the_time
work properly because they can pull the info for the current post in the loop. For more information, read The codex data on WP_Query
and multiple loops