記事一覧を出力した際などの戒め。
こういうこと
これの
<?php
$args = array(
'post_type' => 'hogehoge',
'post_status' => 'publish',
);
$the_query = new WP_Query($args);
if ( $the_query->have_posts() ) :
?>
<ul>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<?php endif; wp_reset_postdata(); ?>
これ。
wp_reset_postdata();
場合によっては書かなくても問題ないけど、セットにする癖をつけた方が幸せに近づける。
どういうことか
ifとかwhileを閉じてもデータを保持してるんで、それをリセットする呪文。
<?php the_title(); ?> ←ページのタイトル
<?php
$args = array(
'post_type' => 'hogehoge',
'post_status' => 'publish',
);
$the_query = new WP_Query($args);
if ( $the_query->have_posts() ) :
?>
~略~
<?php endif; ?>
<?php the_title(); ?> ←WP_Query()で引っ張ったページのタイトル
<?php wp_reset_postdata(); ?>
<?php the_title(); ?> ←ページのタイトル
リセットしないと表示ページのthe_title()とかthe_content()とかが死ぬ。
そういうこと。
注意点
- WP_Query → wp_reset_postdata
- get_posts → wp_reset_postdata
- query_post → wp_reset_query
書き方により変わる。
詳しい記事を読むのがいいです。

取得した情報をリセットする wp_reset_query と wp_reset_postdata | KoMariCote
wp_reset_query と wp_reset_postdata の使い方と違いをメモしています。WordPressのループ処理に必要なこともあるので、覚えておくと役立ちます。
コメント