2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【WordPress】特定の期間内に投稿された記事、更新された記事を取得する方法

Last updated at Posted at 2019-02-26

特定の期間に投稿&更新された記事の取得方法を備忘録として書いていきます。

記事取得にはget_posts()を利用する

今回は、get_posts()を利用して期間内の投稿データを取得します。query_posts()は非推奨なので利用しないようにしましょう。

query_posts()が非推奨な理由

get_posts() は単にデータを取得するだけで、グローバル変数$wp_queryには影響を与えないのに対して、query_posts() はグローバル変数$wp_queryを変更します。つまりメインループに影響を与えるということです。なので、wp_reset_query()の記述を忘れると、他のページのクエリも書き換わってしまうなどの意図しない結果が表示される危険性があったりします。
現在は、サブループではWP_Query()get_posts()を使うことが強く推奨されています。

特定期間に投稿された記事取得

特定の期間内に投稿されたデータを取得するには、date_queryパラメータを利用します。date_queryパラメータの値に配列で情報を付与することで期間内のデータを取得することができます。

<?php
//パラメータを指定
$args = array(
    'posts_per_page' => 10, //記事を10件表示
    'date_query' => array(
        'after' => '2019-1-1',
        'before' => '2019-2-28',
        'inclusive' => true //afterとbeforeに指定した日を含めるかどうか
     )
);
//get_posts()を使って投稿データの配列を取得
$period_posts = get_posts($args);

foreach ($period_posts as $period_post): setup_postdata($post);
?>
    <h3><?php the_title(); ?></h3>
<?php
endforeach; 
//メインクエリの投稿データを復元
wp_reset_postdata(); 
?>

特定期間に更新された記事取得

特定の期間内に更新されたデータを取得するには、条件の連想配列にcolumnキーとしてpost_modifiedを指定すればいい形となります。
ちなみに、columnには下記の6つの値が指定できるようです。

  • post_date(デフォルト値)
  • post_date_gmt
  • post_modified
  • post_modified_gmt
  • comment_date
  • comment_date_gmt
<?php
//パラメータを指定
$args = array(
    'posts_per_page' => 10, //記事を10件表示
    'date_query' => array(
        'after' => '2019-1-1',
        'before' => '2019-2-28',
        'column' => 'post_modified', //更新日時を検索対象に指定
        'inclusive' => true //afterとbeforeに指定した日を含めるかどうか
     )
);
//get_posts()を使って投稿データの配列を取得
$period_posts = get_posts($args);

foreach ($period_posts as $period_post): setup_postdata($post);
?>
    <h3><?php the_title(); ?></h3>
<?php
endforeach; 
//メインクエリの投稿データを復元
wp_reset_postdata(); 
?>
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?