對於類似釋出各種活動通知或到期時間內容的 WordPress 站點,也許會需要這樣一個功能:釋出活動內容的時候設定活動的到期日期,當活動還沒有
過期,網頁顯示 「進行中」;當活動已過了設定的日期,網頁則顯示 「已到期」 或者不再顯示該文章。有了這個功能,WordPress 站長就不需要每次在活動
過期後再編輯文章,實現的方法可以透過 WordPress 內建的自定義欄位。
建立日期自定義欄位:
欄位名稱使用:expiration
設定日期的格式必須是:mm/dd/yyyy 00:00:00 如:01/01/2015 00:00:00
修改主題模板:
編輯當前使用的 WordPress 模板,修改文章主迴圈程式碼:
<?php if (have_posts()) : while (have_posts()) : the_post(); $expirationtime = get_post_custom_values('expiration'); if (is_array($expirationtime)) { $expirestring = implode($expirationtime); } $secondsbetween = strtotime($expirestring)-time(); if ( $secondsbetween > 0 ) { ?> <div id="post-<?php the_ID();?>"> <h2><?php the_title();?></h2> <div > <?php the_excerpt();?> </div> </div> <?php } endwhile; endif; ?>
上面程式碼的作用是如果當前時間超過設定的時間,文章則不顯示。
編輯當前使用的主題模板,修改文章主迴圈程式碼:
<?php if (have_posts()) : while (have_posts()) : the_post(); ?> <div id="post-<?php the_ID();?>"> <h2><?php the_title();?></h2> <div > <?php the_excerpt();?> <?php $expirationtime = get_post_custom_values('expiration'); if (is_array($expirationtime)) { $expirestring = implode($expirationtime); } $secondsbetween = strtotime($expirestring)-time(); if ( $secondsbetween > 0 ) { echo '進行中'; }else { echo '已過期'; } ?> </div> </div> <?php endwhile; endif; ?>
上面程式碼的作用是如果當前時尚沒有超過設定的時間內容中就顯示 「進行中」,否則就顯示 「已過期」 。