WordPressで現在クエリされているオブジェクトを取得する方法

ここでは、WordPressで現在クエリされているページのオブジェクトを取得する方法について説明していきます。

get_queried_object()

WordPressで現在クエリされているページのオブジェクトを取得するには、get_queried_object()を用います。

使用例1

<?php print_r(get_queried_object()); ?>

出力結果1

WP_Post Object ( [ID] => 375 [post_author] => 1 [post_date] => 2024-10-15 07:25:42 [post_date_gmt] => 2024-10-14 22:25:42 [post_content] =>
テスト投稿のコンテントです。

[post_title] => テスト [post_excerpt] => テスト投稿の抜粋です。 [post_status] => publish [comment_status] => open [ping_status] => open [post_password] => [post_name] => %e3%83%86%e3%82%b9%e3%83%88 [to_ping] => [pinged] => [post_modified] => 2024-10-15 07:30:53 [post_modified_gmt] => 2024-10-14 22:30:53 [post_content_filtered] => [post_parent] => 0 [guid] => http://localhost/Yagi-System-coding/?p=375 [menu_order] => 0 [post_type] => post [post_mime_type] => [comment_count] => 0 [filter] => raw )

使用例2

<ul class="queried-object-list">
  <li class="queried-object-list__item">
    <?php
    $queriedObject = get_queried_object();
    echo $queriedObject->ID;
    ?>
  </li>
  <li class="queried-object-list__item">
    <?php
    echo $queriedObject->post_author;
    ?>
  </li>
  <li class="queried-object-list__item">
    <?php
    echo $queriedObject->post_title;
    ?>
  </li>
  <li class="queried-object-list__item">
    <?php
    echo $queriedObject->post_excerpt;
    ?>
  </li>
</ul>

出力結果

・375
・1
・テスト
・テスト投稿の抜粋です。

まとめ

上記のように、get_queried_object()を用いることで、現在クエリされているページのオブジェクトを取得することができます。