好的,我正在为我的WordPress网站制作博客页面。我的首页显示为静态,因此我的博客帖子位于另一个名为“日记”的页面上我想以类似存档的方式显示帖子。我正在努力实现以下目标:
我研究了如何做到这一点,并找到了一种方法;但是,它将所有帖子的日期显示为“11月30日”
这是我正在使用的代码:
<?php
// Get years that have posts
$years = $wpdb->get_results( "SELECT YEAR(post_date) AS year FROM wp_posts WHERE post_type = \'post\' AND post_status = \'publish\' GROUP BY year ASC" );
// For each year, do the following
foreach ( $years as $year ) {
// Get all posts for the year
$posts_this_year = $wpdb->get_results( "SELECT ID, post_title FROM wp_posts WHERE post_type = \'post\' AND post_status = \'publish\' AND YEAR(post_date) = \'" . $year->year . "\'" );
// Display the year as a header
echo \'<h1>\' . $year->year . \'</h1>\';
// Start an unorder list
echo \'<ul class="posts-in-year">\';
// For each post for that year, do the following
foreach ( $posts_this_year as $post ) {
// Display the title as a hyperlinked list item
echo \'<li><a href="\' . get_permalink($post->ID) . \'">\' . $post->post_title . \'</a>\' . \' \' . \'—\' . \' \' . get_the_time(\'F j\') . \'</li>\';
}
// End the unordered list
echo \'</ul>\';
}
?>
基本上,我试图从每个帖子中获取时间并显示其月份和日期(F j)
最合适的回答,由SO网友:Manny Fleurmond 整理而成
功能get_the_time
仅设计用于在主WordPress循环或自定义循环中使用WP_Query
, 因此,您使用它的方式无法正常工作。以下是使用它的正确方法,使用自定义WP_Query
回路:
<?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>\';
}
?>
我之前提到的循环是
WP_Query
为您遍历帖子。当你这样做的时候
get_the_time
工作正常,因为他们可以在循环中提取当前帖子的信息。有关更多信息,请阅读
WP_Query
and multiple loops