wp_reset_postdata() - | KoMariCote

wp_reset_postdata()

the_post() の投稿記事をリセットする

WP_Queryget_posts() などを使用してサブループを回した場合、グローバル変数である $post やメインクエリを主体とした様々な情報を更新しています。サブループの状態のままにすることによって意図せずエラーになってしまうこともあるため初期状態に戻すようにします。

wp_reset_postdata() はサブループを回す際に取得したデータをメインクエリの状態に戻すためのテンプレートタグです。

使い方

wp_reset_postdata()

【返り値】なし

【パラメーター】なし

詳細・注意事項

<?php
  // 取得したい投稿内容
  $args = array(
    'post_type' => 'my_posts',
    'posts_per_page' => 3,
    'category' => '10',
    'no_found_rows' => true;
  );
  // オブジェクト取得
  $my_posts = new WP_Query($args);
  // ループの開始
  while ($my_posts->have_posts()):
    $my_posts->the_post();
?>

<!-- 表示させたい投稿内容 -->
<h1><?php the_title(); ?></h1>
<div><?php the_content(); ?></div>

<!-- 投稿表示終了。メインクエリの値に戻す -->
<?php endwhile; wp_reset_post_data();?>

公式コードファイルとドキュメントはこちら

/wp-includes/query.php

wp_reset_postdata() - WordPress.org

コード Reference 一覧へ