函数文档

get_queried_object()

💡 云策文档标注

概述

get_queried_object() 是 WordPress 中用于检索当前查询对象的函数,作为 WP_Query::get_queried_object() 的包装器。它根据页面类型返回相应的对象,如 WP_Term、WP_Post、WP_Post_Type 或 WP_User。

关键要点

  • 函数返回当前查询对象,类型可能为 WP_Term、WP_Post_Type、WP_Post、WP_User 或 null。
  • 在不同页面类型下返回不同对象:分类归档页返回 WP_Term,文章归档页返回 WP_Post_Type,作者归档页返回 WP_User,单篇文章或页面返回 WP_Post。
  • 需注意与 get_post() 或 global $post 的区别,例如在显示文章的页面中,get_queried_object() 返回页面对象,而 get_post() 返回循环中的当前文章。

代码示例

function get_queried_object() {
    global $wp_query;
    return $wp_query->get_queried_object();
}

注意事项

避免与 get_post() 或 global $post 混淆使用,特别是在非单篇文章页面,如文章列表页,它们可能返回不同对象。


📄 原文内容

Retrieves the currently queried object.

Description

Wrapper for WP_Query::get_queried_object().

Return

WP_Term|WP_Post_Type|WP_Post|WP_User|null The queried object.

Source

function get_queried_object() {
	global $wp_query;
	return $wp_query->get_queried_object();
}

Changelog

Version Description
3.1.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    The “currently-queried object” means the object that is the subject of the webpage:

    – On a category archive, tag archive, or other taxonomy archive page, it will return the WP_Term object of the current category, tag, or other term.
    – If you have set a posts page where your basic posts are displayed, get_queried_object() will return the WP_Post object of that page.
    – On post type archive pages, it will return the WP_Post_Type object of the given post type.
    – On an author archive page, it will return the WP_User object of that author.
    – On any singular page (a single post, a single page, or a post in a custom post type), it will return the WP_Post object of that post or page.

    Be careful not to use get_queried_object() and get_post() or global $post interchangeably. On a singular post, those will all return the same thing. But, for example, if you have a page called “Blog” that displays your posts, get_queried_object() will return the “Blog” page whereas get_post() will return the current post in the loop.