WordPress 投稿から任意の時間が経過した記事一覧を表示

/ WordPress / Comment[0]

たとえば、1ヶ月~2ヵ月経過した記事だとか1年から2年経過した記事一覧を表示する方法

<?php
//現在のUnixタイム
$current_date = date( 'Y-m-d', strtotime( 'now' ) );

//対象の投稿を全て引っ張る
query_posts( 'post_type=project&posts_per_page=-1' );
while( have_posts() ) : the_post();

  //公開日
  $the_time = the_time( 'Y-m-d' );
  //公開日のUNIXタイム
  $publish_date_unix = strtotime( $the_time . 'now' );

  //現在時間-経過時間
  $publish_date_1 = strtotime( $current_date . '-1 month' );
  $publish_date_2 = strtotime( $current_date . '-2 month' );
  $publish_date_3 = strtotime( $current_date . '-3 month' );
  $publish_date_4 = strtotime( $current_date . '-4 month' );
  $publish_date_5 = strtotime( $current_date . '-5 month' );
  $publish_date_6 = strtotime( $current_date . '-6 month' );
  $publish_date_12 = strtotime( $current_date . '-12 month' );
  $publish_date_24 = strtotime( $current_date . '-24 month' );

  switch( $publish_date ) {
    //1~2ヵ月前の投稿IDを取得
    case ( $publish_date_2 < $publish_date_unix && $publish_date_unix <= $publish_date_1 ) :
      $publish_date_1_posts[] = $post->ID;
    break;
    //2~3ヶ月前の投稿IDを取得
    case ( $publish_date_3 < $publish_date_unix && $publish_date_unix <= $publish_date_2 ) :
      $publish_date_2_posts[] = $post->ID;
    break;
    //3~4ヶ月前の投稿IDを取得
    case ( $publish_date_4 < $publish_date_unix && $publish_date_unix <= $publish_date_3 ) :
      $publish_date_3_posts[] = $post->ID;
    break;
    //5~6ヶ月前の投稿IDを取得
    case ( $publish_date_6 < $publish_date_unix && $publish_date_unix <= $publish_date_5 ) :
      $publish_date_6_posts[] = $post->ID;
    break;
    //6~12ヶ月前の投稿IDを取得
    case ( $publish_date_12 < $publish_date_unix && $publish_date_unix <= $publish_date_6 ) :
      $publish_date_12_posts[] = $post->ID;
    break;
    //1~2年前の投稿IDを取得
    case ( $publish_date_24 < $publish_date_unix && $publish_date_unix <= $publish_date_12 ) :
      $publish_date_24_posts[] = $post->ID;
    break;
  }

endwhile;
?>

switchで投稿日の期間ごとに振り分け、配列に突っ込んだので、それぞれをforeachなりで回転させればおk

<div class="column">
  <p class="title-4">1ヶ月~2ヶ月</p>
  <ul class="default">
  <?php foreach( $publish_date_1_posts as $post ) : ?>
    <li>
      <a href="<?php the_permalink(); ?>">
        <?php the_title(); ?> <?php the_time( 'Y-m-d' ); ?>
      </a>
    </li>
  <?php endforeach; ?>
  </ul>
</div>

<div class="column">
  <p class="title-4">2ヶ月~3ヶ月</p>
  <ul class="default">
  <?php foreach( $publish_date_2_posts as $post ) : ?>
    <li>
      <a href="<?php the_permalink(); ?>">
        <?php the_title(); ?> <?php the_time( 'Y-m-d' ); ?>
      </a>
    </li>
  <?php endforeach; ?>
  </ul>
</div>
:

foreachでIDを$postに入れることで、そのままforeach中でthe_time(),the_permalink()などのWP関数が使えます。

関連記事

コメント

:
:
:
:
:
管理人のみ表示を許可