[WordPress小ネタ]時限公開リンクのショートコード
指定期間を過ぎたらリンクタグのみ除外したい、という要望があったので作ってみた小ネタ。
キャッシュプラグインやnginxでページキャッシュを有効にしている場合は、取下げ時刻にキャッシュクリアする必要があるのでご注意ください。
■使用例
*中のテキストもまるごと取り下げたい
[limit_link href="http://www.google.com" end="2016-03-05 01:51:00"]サンプルテキスト[/limit_text]
*リンクだけ取り下げたい+別ウィンドウで開く
[limit_link href="http://www.google.com" end="2016-03-05 01:51:00" target="_blank" text="show"]サンプルテキスト[/limit_link]
function custom_shortcode_limit_link( $atts, $content = null ) {
extract( shortcode_atts( array(
'href' => 'http://example.com/',
'target' => '_self',
'end' => '2015-12-31 23:59:59',
'text' => 'hide'
), $atts ) );
$now = date_i18n('U'); // 現在の時刻
$expire_date = date('U',strtotime($end)); // 取り下げ時刻
if($expire_date >= $now) {
// リンク掲出期間中
return '<a href="' . esc_html($href) . '" target="' . esc_html($target) . '">' . esc_html($content) . '</a>';
} elseif ($text === 'show') {
// 掲出終了後、テキストは表示する場合
return esc_html($content);
} else {
// 掲出終了後、丸ごと消す場合
return;
}
}
add_shortcode('limit_link', 'custom_shortcode_limit_link');