人们常常对如何从全局对象/变量获取数据感到困惑
Question: 您可以通过哪些方式检查全局变量?写这篇Q是因为华盛顿经常需要它。我只是想把它作为一个fav链接到这里(人们通常不看github的gist链接)。
如果有什么地方不对,或者您认为解释遗漏了什么,请随意修改示例。如果您想添加其他有用的内容,请将每个内容添加为单个答案。谢谢你
写这篇Q是因为华盛顿经常需要它。我只是想把它作为一个fav链接到这里(人们通常不看github的gist链接)。
如果有什么地方不对,或者您认为解释遗漏了什么,请随意修改示例。如果您想添加其他有用的内容,请将每个内容添加为单个答案。谢谢你
function inspect_wp_query()
{
echo \'<pre>\';
print_r($GLOBALS[\'wp_query\']);
echo \'</pre>\';
}
// If you\'re looking at other variables you might need to use different hooks
// this can sometimes be a little tricky.
// Take a look at the Action Reference: http://codex.wordpress.org/Plugin_API/Action_Reference
add_action(\'shutdown\', \'inspect_wp_query\', 999); // Query on public facing pages
add_action(\'admin_footer\', \'inspect_wp_query\', 999); // Query in admin UI
顺便说一句: // this:
global $wp_query;
$wp_query;
// is the same as
$wp_query;
// and as this:
$GLOBALS[\'wp_query\'];
// You can do this with each other global var too, like $post, etc.
如何实际获取数据:// Example (not the best one)
(Object) WP_Query -> post (stdClass) -> postdata (Array)
// How to get the data:
// Save object into var
$my_data = new WP_Query; // on a new object
// or on the global available object from the current request
$my_data = $GLOBALS[\'wp_query\'];
// get object/stdClass "post"
$my_post_data = $my_data->post;
// get Array
$my_post_data = $my_data[\'post\'];
示例Generate a drop down/select object with all sidebars inside the global $wp_registered_sidebars
或者,如果你懒惰,只需安装Debug Bar 插件。
它在管理栏中添加了一个按钮,单击该按钮后,将显示一个包含各种有用信息的面板,包括弃用通知、WP\\U查询变量和SQL查询日志。
根据加载脚本和呈现最终输出过程中的位置,上述一些变量可能不存在。如果您想要一个相当全面的视图,可能有点极端,请尝试:
var_dump($GLOBALS);
var\\u dump还可以告诉您数据的类型和格式。