Skip to content

Instantly share code, notes, and snippets.

@gatespace
Created May 28, 2012 06:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gatespace/2817701 to your computer and use it in GitHub Desktop.
Save gatespace/2817701 to your computer and use it in GitHub Desktop.
WordPressの本文の内容を指定日時によって表示するショートコード
<?php
/**
* @package datecontent_shortcode
* @version 1.0
*/
/*
Plugin Name: 指定日時によって内容を表示するショートコード
Plugin URI: https://gist.github.com/2817701
Description: WordPressの本文の内容を指定日時によって表示するショートコード。使い方は [datecontent opendate="YmdHi" closedate="YmdHi"]指定日時で表示する内容[/datecontent] です。opendate で表示の開始日時、closedate で表示の終了日時をYmdHiの形式で指定します。
Author: gatespace
Version: 1.0
Author URI: http://gatespace.wordpress.com/
*/
// [datecontent opendate="YmdHi" closedate="YmdHi"]
function datecontent_func($atts, $content = null) {
extract(shortcode_atts(array(
'opendate' => null,
'closedate' => null,
), $atts));
/**
* $opendate, $closedateの値をチェック(8〜12桁の数字)し
* 正しい年月日、時刻かチェックしてUnixのタイムスタンプに
*/
$dates = array( "opendate" => $opendate, "closedate" => $closedate );
foreach ($dates as $key => $val) {
// 8〜12桁の数字の数字で入力されているかどうかチェック
if ( (!preg_match("/^[0-9]{8,12}$/", $val)) or ($val === null) ) {
$dates[$key] = null;
continue;
} else {
// 正しい日付かどうかチェック(違うときはnullで終了)
$dates_Y = substr($val, 0, 4);
$dates_M = substr($val, 4, 2);
$dates_D = substr($val, 6, 2);
if (!checkdate($dates_M, $dates_D, $dates_Y )) {
$dates[$key] = null;
continue;
}
// 正しい時刻かどうかチェック(違うときは00:00)
$dates_H = ( substr($val, 8, 2) && preg_match("/(0|1)[0-9]|2[0-3]/", substr($val, 8, 2) )) ? substr($val, 8, 2) : "00";
$dates_I = ( substr($val, 10, 2) && preg_match("/[0-5][0-9]/", substr($val, 10, 2) )) ? substr($val, 10, 2) : "00";
// mktimeでUnixのタイムスタンプに
$dates[$key] = mktime($dates_H, $dates_I, 0, $dates_M, $dates_D, $dates_Y);
}
}
$nowdate = date_i18n('U'); // 現在の時間を取得しUnixのタイムスタンプに
if ( ($dates["opendate"] === null) && ($dates["closedate"] === null)) {
return $content;
} elseif ($dates["closedate"] === null) {
if ($nowdate >= $dates["opendate"]) {
return $content;
}
} elseif ($dates["opendate"] === null) {
if ($nowdate < $dates["closedate"]) {
return $content;
}
} else {
if ( ($nowdate >= $dates["opendate"]) && ($nowdate < $dates["closedate"]) ) {
return $content;
}
}
}
add_shortcode('datecontent', 'datecontent_func');
@gatespace
Copy link
Author

Twitterで助言をいただき
・opendate、closedateが数字かどうかのチェック
・opendate、closedateの日付のチェック(falseの時はnull)
・opendate、closedateの時刻のチェック(falseの時は00代入)
・日時の比較をUNIXタイムスタンプにする
の処理を追加し、WordPressのプラグインとして動作するようにしました。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment