wordpress で記事内に時限公開shortcodeを作成
table contenswordpress でよくある要望として、ある日時になったら表示したいブロックがある。
たとえば、プレゼント企画で事前に応募開始日を予告し、同じ記事内で開始日に
応募ページのリンクを表示するなどである。
1 例
1.1 応募開始日前
<h3>素敵なクリスマスプレゼント!</h3>
12/20 に応募開始です。
1.2 応募開始後
<h3>素敵なクリスマスプレゼント!</h3>
<!-- 12/20 に応募開始です。 -->
応募ページは、 <a href="xxxxx">こちら</a>です。
2 サンプルコード
2.1 action or filter
shorcode open_date_view を追加
2.2 source code
| function shortcode_open_date_view($atts = '', $content = '') { | |
| $tz = new DateTimeZone('Asia/Tokyo'); | |
| // get now | |
| $now = new DateTime('now', $tz); | |
| $format = 'Y-m-d H:i:s'; | |
| // get argment | |
| extract(shortcode_atts([ | |
| 'open' => ''], $atts)); | |
| // get argment open_date | |
| $open_date = DateTime::createFromFormat($format, $open, $tz); | |
| if ($now > $open_date) { | |
| // view contents | |
| // do shortcode in this shortcode | |
| $content_expand = do_shortcode($content); | |
| return $content_expand; | |
| } else { | |
| // not yet open date | |
| return ''; | |
| } | |
| } | |
| add_shortcode('open_date_view', 'shortcode_open_date_view'); |
2.3 open_date_view の投稿画面の記述例
<h3>素敵なクリスマスプレゼント!</h3>
[open_date_view open='2018-12-20 00:00:00']<!--[/open_date_view]
12/20 に応募開始です。
[open_date_view open='2018-12-20 00:00:00']-->[/open_date_view]
[open_date_view open='2018-12-20 00:00:00']
応募ページは、 <a href="xxxxx">こちら</a>です。
[/open_date_view]
3 解説
3.1 add_shortcode
追加したい shorcode を宣言する。
add_shortcode('open_date_view', 'shortcode_open_date_view');
第1引数の open_date_view が、 [open_date_view]xxxxx[/open_date_view]
というように 投稿画面の記事中で利用できるようになる。
3.2 引数解析
shortcode の引数解析は、 関数 shortcode_atts を利用し、取得したい変数名を指定する。
関数 extract は、php の関数で、シンボルテーブルをコード上で直接変数として使えるようにimportする。
extract(shortcode_atts([
'open' => ''], $atts));
echo $open; // open_date_view の open引数の内容
3.3 shortcode内のshortcode
shortcode の処理で気を付けたいのが、 shortcode のコンテンツ部分で shortcode を利用することがある。
[open_date_view open='2018-12-20 00:00:00']
あああああ
[dott]
いいいいい
[/open_date_view]
サンプルコードにあるように、 関数 do_shortcode を実施しなければ、
[dott] はそのままの文字列 [dott] として表示される。