web関連

【wordpress】ACFのDatePicker値の後ろ1か月以内の記事を表示

【wordpress】ACFのDatePicker値の後ろ1か月以内の記事を表示

投稿記事内のカスタムフィールドDatePickerの値を基準に「年」を無視した1ヶ月後以内の記事のみ表示させようとしたときの備忘録

datepickerの値を基準にした1か月後以内の記事の出力方法

先に言っておくと未完成
※Dp = datepickerの省略

<?php 
	$today = date_i18n('Y-m-d');//今日の日時取得
	$args = array(
		'posts_per_page' => -1,
		'post_type' => 'post',
	);
	$the_query = new WP_Query($args);
	if ( $the_query->have_posts() ) :
	while ( $the_query->have_posts() ) : $the_query->the_post();
?>
	<?php
	$acf_datepicker = get_post_meta( get_the_ID(), 'ACFのDp入る', true );

	if ($acf_datepicker) {
		$date = date_create( $acf_datepicker );
		$selectday = date_format($date,'Y-m-d');
		$display = date_format($date,'Y年m月d日');

		//Dpに入力があるかどうか
		if ($acf_datepicker) {
			//現在の日時が記事のDpを超えてたら1年加算
			if(strtotime($selectday) < strtotime($today)) {
				$plus_1year = date('Y-m-d',strtotime('+1year',strtotime($selectday)));
			}

			//変数に代入
			if ($plus_1year) {
				$modified = $plus_1year;
			}else{
				$modified = $selectday;
			}

			//現在の日時と比較して1か月以内の記事は出力
			if(strtotime("now -1 month") < strtotime($modified) && strtotime("now +1 month") > strtotime($modified)):?>
				
			<a href="<?php the_permalink(); ?>">
				<?php echo $display;//Dpの日時出力 ?>
				<?php the_title(); ?>
			</a>

			<?php else://期間外 ?>
			<?php endif; ?>
			<?php 
			$plus_1year='';//変数の初期化
		}
	}
	?>
	<?php endwhile; ?>
<?php endif ?>

今回のコードは現在の月日より「後ろ」しか判別できない
だから「現在(10月20日)~1か月後(11月20日)」はできるけど「1か月前(9月20日)~現在(10月20日)」の記事はコード書き換えないとできない

というのも12月から1月になったときの扱いがよくわからず、現在の月日以下の値を持つ記事を1年加算させることでなんかいい感じに整えているから「1か月前(9月20日)~現在(10月20日)~1か月後(11月20日)」っていうような要望の時$plus_1yearが邪魔になる

とりあえず要望としては十分なので12月から1月を跨ぐときの処理は後で暇なときに調べようと思う

時間周りの処理方法本当によくわからない

Leave a Comment

入力エリアすべてが必須項目です。メールアドレスが公開されることはありません。

内容をご確認の上、送信してください。