日付を比較して投稿を表示する
PR
最近、日付を操作して何かすることが多いので、メモ。
2つの日付を比較
今日、未来、過去日なのかを判定する場合のコード
$today = date('Y-m-d');
$oneday = $field['oneday']; //カスタムフィールドの日付
if(strtotime($today) === strtotime($oneday)){
var_dump('今日');
} else if(strtotime($today) < strtotime($oneday)){
var_dump('未来');
} else {
var_dump('過去');
}
イベント時、日付毎に一覧表示
ユーザーに日付を選択してもらい、指定期間分の投稿を返すし、日付ごとに投稿を表示する場合のサンプル。 一部抜粋して掲載しているので、下記コードは正常に動作しない可能性があります。
//日付を取得
$today = date('Y-n-d');
list($y, $m, $d) = preg_split('/-/', $today);
//投稿を取得
global $post;
$my_posts = get_posts(array(
'post_type' => 'post',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
));
$date = $today;
//曜取得
$datetime = new DateTime($date);
$week = array("日", "月", "火", "水", "木", "金", "土");
$w = (int)$datetime->format('w');
$w = $week[$w];
$chk = array(); //判定用
//日付順に並べて表示
$html .= '<h2>' .$m.'月'.$d.'日('.$w.')</h2>'; //表示日時
//投稿に指定日が含まれる場合のみ取得する
foreach($my_posts as $post){
setup_postdata($post);
$fields = get_field('dates');
//日付取得・判定
$show = in_array( $date, array_column( $fields, 'oneday') ,true);
if($show === true ){
$count[] = $i++;
$chk[] = 'true';
echo '<a href="' . get_permalink() . '">';
echo get_the_title();
echo '<p>'.$post->post_content).'</p>';
echo '</a>';
} else {
$chk[] = 'false';
}
}