問題描述
我有自定義帖子型別”press.” 並且做了頁面模板的型別的查詢帖子。這些帖子應該顯示其釋出的日期,但如果同一日期有多個帖子,則只有第一個帖子顯示日期,而其他帖子不顯示。有沒有辦法顯示每個帖子的日期?
<?php get_header(); ?>
<?php
$wp_query = new WP_Query();
$wp_query -> query('post_type=press&showposts=100');
while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
<div id="press">
<div class="press-item cf">
<div class="press-img"><a href="<?php%20the_field('link');%20?>"><?php the_post_thumbnail('medium');?></a> </div>
<div class="press-content">
<div class="press-title"><a href="<?php%20the_field('link');%20?>"><?php echo get_the_title(); ?></a> </div>
<div class="press-excerpt"><?php the_excerpt(); ?> </div>
<div class="press-date"><?php the_date(); ?></div>
</div>
</div>
</div>
<?php endwhile; ?>
<?php get_footer(); ?>
最佳解決方案
我以前遇到類似的問題,因為我修改了我的日期功能。然後帖子顯示日期,如果只有每個帖子有不同的日期,否則返回空白。
嘗試新增<?php echo get_the_date(); ?> 。
次佳解決方案
為什麼不顯示?
當您檢視 the_date()函式的原始碼時,將會注意到兩個全域性變數:
global $currentday, $previousday;
然後有一個規則,如果有一個日期顯示… 或不。檢查類似於使用 is_new_day()完成的檢查:
if ( $currentday != $previousday ) {
// show date
// Set global
$previousday = $currentday;
}
// else
return null;
您可以看到,$previousday 立即設定為 $currentday; 。所以它得到 echo-ed 一次。在這之後,兩天都是一樣的,檢查將失敗。這就是為什麼你的第一篇文章顯示它,但其他人不顯示它的原因。
為什麼會顯示?
如果你問自己為什麼它會顯示多個日期,在全球化得到平衡後,你將不得不看看 setup_postdata()。此功能由 the_post(); 呼叫,負責為迴圈中的單個帖子設定所有內容。
if ( have_posts() )
{
while ( have_posts() )
{
the_post(); # <-- Calls setup_postdata( $post );
// your loop stuff here
}
}
setup_postdata()的內部元件很容易理解 (至少全域性變數設定):
$currentday = mysql2date('d.m.y', $post->post_date, false);
$currentmonth = mysql2date('m', $post->post_date, false);
所以移動部分是 $previousday,$currentday 全域性被設定和檢查。除非有新的一天,否則 the_date()不會顯示任何內容。
只需將您的帖子設定為完全不同的日子,突然您將看到日期顯示在每個帖子上。
這背後有什麼想法?
實際上,這個想法自 v0.7.1 起是非常簡單和現實的 – 至少這是 phpDocBlock 所說的:為什麼要在檔案中顯示每個帖子的日期?檔案看起來像這樣:
+--------------+
| 28.10.2014 |
+--------------+
| Post Title A |
| Post Title B |
+--------------+
| 29.10.2014 |
+--------------+
| Post Title C |
| Post Title D |
+--------------+
你不同意嗎?那麼你只是使用一個完全不同的功能。
為什麼 get_the_date()可以正常工作,如何使用它
它不受 the_date()函式中的 if /else(全域性檢查) 的影響。它也沒有過濾器。如何解決?簡單:
echo apply_filters( 'the_date', get_the_date(), get_option( 'date_format' ), '', '' );
這將新增到 the_date 過濾器的任何回撥到您的自定義輸出。它也使用預設的 date_format 選項設定作為預設值 – 也由 the_date()使用。它也避免了任何 before 和 after 的功能,與 the_date()功能完全相同。
第三種解決方案
不要使用 the_date(),而是使用 the_time()。
the_date 返回日期,the_time 返回日期+時間。當 the_date 在一個迴圈中使用時,我不知道 wordpress 不會返回多個日期的原因。但它與值相同的事實有關。如果使用 the_time,值將永遠不變,因此它始終返回值。所以你可以列印像<?php the_time('F j, Y'); ?>
來自 Codex 的 link 解釋了 the_date 的工作原理比我好多了。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。
