WordPressでバナーを公開日時またはリンク先が公開されている場合のみ表示したい
WordPressで「指定した公開日時になったらバナーを表示したい」「バナーのリンク先ページが公開されている場合のみバナーを表示したい」けど、WordPressの標準機能やテーマの機能ではできない…と思ったことはありませんか?
今回はそんな時に使用できるショートコードをご紹介します。
目次
公開日時またはページが公開されている場合に内容を表示するショートコード
下記コードをfunctions.phpに追記します。
/**
* 条件に応じてコンテンツを表示するショートコード
*/
add_shortcode( 'display_content_when_conditions', function( $atts, $content = null ) {
// 公開日時とページのIDがどちらも指定されていない場合
if ( ! empty( $atts['target_date'] ) && ! empty( $atts['published_post_id'] ) ) {
return '';
}
// 公開日時が指定されている場合
if ( ! empty( $atts['target_date'] ) ) {
// タイムゾーン
$timezone = new DateTimeZone( 'Asia/Tokyo' );
// 現在日時
$current_date = new DateTimeImmutable( wp_date( 'Y-m-d H:i' ), $timezone );
// 公開日時
$target_date = new DateTimeImmutable( $atts['target_date'], $timezone );
// 現在日時が公開日時になった場合
if ( $current_date >= $target_date ) {
return do_shortcode( shortcode_unautop( $content ) );
} else {
return '';
}
}
// 指定したIDのページが公開されている場合
if ( ! empty( $atts['published_post_id'] ) && get_post_status( $atts['published_post_id'] ) === 'publish' ) {
return do_shortcode( shortcode_unautop( $content ) );
} else {
return '';
}
} );
使い方
例)指定した公開日時(2030年1月1日の0時0分)になったらbanner.jpgを表示する場合
target_dateに「Y-m-d H:i」の形式で指定します。2029年12月30日の23時59分まで非表示で、2030年1月1日の0時0分から表示されます。
カスタムHTMLブロックの場合
[display_content_when_conditions target_date="2030-01-01 00:00"]
<img src="banner.jpg" alt="">
[/display_content_when_conditions]
テーマのテンプレートに直接書く場合
<?php
$content = '<img src="banner.jpg" alt="">';
echo do_shortcode('[display_content_when_conditions target_date="2030-01-01 00:00"]' . $content . '[/display_content_when_conditions]');
?>
例)指定したID(123)のページが公開されていればbanner.jpgを表示する場合
published_post_idにバナーのリンク先ページのIDを指定します。IDは編集画面のURLに付与されている「?post=」の数字です。123というIDのページが公開されていなければ非表示、公開されていれば表示されます。※123は例です。
カスタムHTMLブロックの場合
[display_content_when_conditions published_post_id="123"]
<img src="banner.jpg" alt="">
[/display_content_when_conditions]
テーマのテンプレートに直接書く場合
<?php
$content = '<img src="banner.jpg" alt="">';
echo do_shortcode( '[display_content_when_conditions published_post_id="123"]' . $content . '[/display_content_when_conditions]' );
?>
作成されていない、または公開以外のステータスの場合は公開されていないとみなされます。
tooolsのTech Blogではこれからも役に立つ情報を発信していきますので、定期的に閲覧していただけると幸いです。
参考:add_shortcode() – Function | Developer.WordPress.org
参考:wp_date() – Function | Developer.WordPress.org
参考:do_shortcode() – Function | Developer.WordPress.org
参考:shortcode_unautop() – Function | Developer.WordPress.org
参考:get_post_status() – Function | Developer.WordPress.org
参考:PHP: DateTimeZone::__construct – Manual
参考:PHP: DateTimeImmutable::__construct – Manual