如何获取每个帖子的日期?


10

我正在使用以下方法获取每个帖子的日期:

while (have_posts()) : the_post();
//some html
<li class="icon-date"><?php the_date('Y-m-d');?></li>
<li class="icon-time"><?php the_date('H:i:s');?></li>

但是,我只知道第一篇文章的发布日期,为什么?

Answers:


21

在过去为我所做的更改之后,我几次遇到相同的问题:

while (have_posts()) : the_post();
//some html
<li class="icon-date"><?php echo get_the_date( 'Y-m-d' ); ?></li>
<li class="icon-time"><?php the_time( 'H:i:s' ); ?></li>

代替the_date()使用get_the_date()
唯一需要注意的是,get_the_date()必须回显由返回的值。

Codex页面上有一个关于的特殊说明the_date()

在同一天下发布的页面上有多个帖子时,the_date()仅显示第一篇帖子的日期(即the_date()的第一个实例)。要为同一天发布的帖子重复日期,您应该使用模板标签the_time()或get_the_date()(从3.0开始),并带有日期特定的格式字符串。

另外,如果要控制get_the_date()在Admin中返回的格式,则可以使用get_option('date_format')。这样,如果您在管理员中更改日期格式,这些更改也将在您的代码中进行。

while (have_posts()) : the_post();
//some html
<li class="icon-date"><?php echo get_the_date( get_option('date_format') ); ?></li>
<li class="icon-time"><?php the_time( 'H:i:s' ); ?></li>

0

同一天下发布的页面上有多个帖子时,the_date()仅显示第一个帖子(即the_date()的第一个实例)的日期。要为同一天发布的帖子重复日期,您应该使用模板标签the_time()get_the_date()(从3.0开始),并带有日期特定的格式字符串。用于添加在管理界面中设置的日期。

有关更多信息,请访问此页面

因此,根据wordpress Codex参考,正确的代码如下:

while (have_posts()) : the_post();
//some html
<li class="icon-date"><?php echo get_the_date('Y-m-d');?></li>
<li class="icon-time"><?php the_time('H:i:s');?></li>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.