0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

global $post が必要なパターンと不要なパターンについて

Last updated at Posted at 2025-02-10

global $post が必要なパターン

  1. メインループの外で投稿データにアクセスする場合
// ループの外で現在の投稿データを取得したい場合
global $post;
$current_post_id = $post->ID;
  1. 関数の中で現在の投稿データにアクセスする場合
function my_custom_function() {
    global $post;
    return $post->ID;
}
  1. 複数のループを扱う際に元の投稿データを保持したい場合
global $post;
$original_post = $post; // 元の投稿を保存

// 新しいクエリ
$custom_query = new WP_Query($args);
while ($custom_query->have_posts()) : $custom_query->the_post();
    // 処理
endwhile;

$post = $original_post; // 元の投稿を復元
wp_reset_postdata();

global $post が不要なパターン

  1. WordPressのメインループ内
while (have_posts()) : the_post();
    // the_title() や the_content() などのテンプレートタグが
    // 自動的に現在の $post を参照する
    the_title();
endwhile;
  1. WP_Queryを使用する場合
$custom_query = new WP_Query($args);
while ($custom_query->have_posts()) : $custom_query->the_post();
    // WP_Queryが自動的に$postを設定する
    the_title();
endwhile;
wp_reset_postdata(); // 重要:元の投稿データを復元
  1. get_posts()を使用する場合
$posts = get_posts($args);
foreach ($posts as $post) {
    setup_postdata($post);
    // ここでテンプレートタグが使える
    the_title();
}
wp_reset_postdata();
  • なぜループ内で不要か?
    WordPressのループ関数(the_post())が自動的に現在の投稿を$postグローバル変数にセットするため

  • なぜ関数内で必要か?
    PHP関数のスコープルールにより、関数内からグローバル変数にアクセスするにはglobal宣言が必要なため

  • なぜWP_Query使用時に不要か?
    WP_Queryクラスのthe_post()メソッドが自動的に$postをセットするため

  • 重要な注意点
    カスタムクエリを使用した後は必ずwp_reset_postdata()を呼び出して、元のメインクエリの状態を復元する。複数のループを扱う場合は、元の$postを変数に保存しておくことが安全

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?