いろんな項目を本文中でタイマー表示させる機能を作りました。
自分ではよく使いそうなのでメモです。
任意のテキストをタイマー表示
(各関数名のスコープなどは適宜)
タイマー関数
functions.php
function start_end_timer($start = null, $end = null) {
//php5.4↑記法
$now = (new DateTime())
->setTimeZone(new DateTimeZone('Asia/Tokyo'))
->format('Y-m-d H:i:s');
//php5.3↑記法
$is_open = (!$start) ?: (strtotime($start) <= strtotime($now));
$not_close = (!$end) ?: (strtotime($now) < strtotime($end));
if ($is_open && $not_close) {
return true;
} else {
return false;
}
}
タイマー関数を使ったテキストを表示するだけのショートコード
functions.php
function timer_text_shortcode($atts,$content=null) {
extract(shortcode_atts(array(
'start' => null,
'end' => null,
), $atts));
if (!start_end_timer($start, $end)) {
return null;
}
return $content;
}
add_shortcode('timer_text', 'timer_text_shortcode');
本文中に書くショートコード
時刻の記述は正確に'Y-m-d H:i:s'で。(自動改行<br>はここではカットしてません。)
[timer_text start='2015-02-04 14:30' end='2015-02-04 15:00']
2/4 14:30~15:00の間のみ表示されるテキスト
[/timer_text]
[timer_text end='2015-02-04 15:00']
2/4 ~15:00で非表示になるテキスト
[/timer_text]
[timer_text start='2015-02-04 15:00']
2/4 15:00~からずっと表示されるテキスト(一つ上のテキストと入れ替え表示になる)
[/timer_text]
ほかの任意のショートコードにもこのタイマー機能を埋め込む
exelファイル読み込んでhtmlに展開する関数と合わせる、などに使えると思います。
functions.php
function some_function_shortcode($atts) {
extract(shortcode_atts(array(
'title' => null,
'file' => null,
//ここにstart,endの引数を追加するだけ
'start' => null,
'end' => null,
), $atts));
if (!start_end_timer($start, $end)) {
return null;
}
return //title,urlなどで何かしらの処理をしたhtml;
}
add_shortcode('some_function', 'some_function_shortcode');
//ショートコードは同様に
//[some_function title=title file=data.xlsx start='2015-02-04 15:00']