GHWEB06.GRASSHOPPER

WordPressで○日以内に書いた記事の一覧を表示

  • Category:Web関連
  • Web関連の備忘録

WordPressで○日以内に書いた記事の一覧を表示させてみました。例えば、トップページ等に古い記事を表示させたくないといった場合に使えるかと思います。

試用バージョン:Wordpress 3.9.1

function.php に下記を記述

function.php にフィルター関数を作成します
日は、strtotime で指定を行い、投稿は、WP_Query で絞り込みます。
ちなみに下記サンプルは30日以内の投稿を絞り込んだ場合です。

function filter_where($where = '') {
   $where .= " AND post_date >= '" . date_i18n('Y-m-d', strtotime('-30 days')) . "'";
   return $where;
}
add_filter('posts_where', 'filter_where');
$args = array(
 'post_type' => 'post',
 );
$my_limit_post =  new WP_Query( $args );
remove_filter( 'posts_where', 'filter_where' );

テンプレートに記述を行う

function.php で指定した $my_limit_post を使って、表示させたいテンプレートの箇所にループを記述します。

<ul>
<?php
if($my_limit_post->have_posts()): while($my_limit_post->have_posts()) : $my_limit_post->the_post(); ?>
<li><?php the_title(); ?></li>
<?php endwhile; ?>
<?php else: ?>
<li>30日以内に書かれた記事はありません</li>
<?php endif; ?>
<?php wp_reset_query(); ?>
</ul>
  • 掲載: