How to: inspect global variables in WordPress

People are often confused about how to get data from global objects/variables

Question: In which ways can you inspect global variables?


This Q was written because it’s needed pretty often over here at WA. I just wanted to have it as a fav to link over here (people often don’t take a look at github gist links).

Feel free to modify the example if something is wrong or you think that the explanation is missing something. If you want to add other useful stuff, please add each as a single answer. Thank you.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Or, if you’re lazy, just install the Debug Bar plugin.

It adds a button to the admin bar that, when clicked, reveals a panel with all kinds of useful information, including deprecation notices, WP_Query variables and an SQL query log.

Method 2

How to inspect the data:

Use this to get an insight view of what you can use from the current request/wp_query.

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

Btw:

    // 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.

How to actually get the data:

// 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'];

Examples

Method 3

Depending on where in process of loading the scripts and rendering the final output, some of the above mentioned variables may not be present. If you want a fairly inclusive view, perhaps a bit extreme, try:

var_dump($GLOBALS);

var_dump is also nice in that tell you the type and formats the data a bit.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x