WordPressで今月分の記事のみを表示する
カスタム投稿の記事で今月分のカスタム投稿の記事のみを表示する方法をメモ
<?php
// 今日の日付を取得
date_default_timezone_set('Asia/Tokyo'); // タイムゾーンの指定(必要なければ削除)
$this_date = date('Y-m-1'); // 今日の日付を元に今月の月初めを取得
$this_year = date('Y', strtotime($this_date)); // 年を取得
$this_month = date('m', strtotime($this_date)); // 月を取得
?>
<?php
$year = get_query_var( 'year' );
$monthnum = get_query_var( 'monthnum' );
$args = array(
'date_query' => array(
array(
'after' => array(
'year' => $this_year, // 今年
'month' => $this_month, // 今月
'day' => 1,
),
'before' => array(
'year' => $this_year, // 今年
'month' => $this_month, // 今月
'day' => 31,
),
'inclusive' => true,
),
),
'post_type' => 'blog', /* カスタム投稿タイプを指定 例)blog*/
'order' => 'date',
'order' => 'ASC', /* 並び順指定*/
'posts_per_page' => -1
);
?>
<?php $my_query = new WP_Query( $args ); ?>
<?php if ( $my_query->have_posts() ) : ?>
<?php while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
<a href="<?php the_permalink(); ?>" rel="bookmark">
<time datetime="<?php the_time('Y-m-d'); ?>">
<?php the_time('Y.m.d'); ?>
</time>
<?php the_title_attribute(); ?>/* 記事タイトル*/
<?php echo wp_trim_words( get_the_content(), 200, '…' ); ?>/* 記事本文200文字だけ取得の例*/
</a>
<?php endwhile; ?>
<?php else : //記事が無い場合の文章表示 ?>
<p>該当する記事がありません。</p>
<?php endif; ?>
