It’s probably more of a PHP question, but I would like to know if there are any differences in using

global $post;
echo $post->ID;

when compared to

echo $GLOBALS['post']->ID;

to access the ID of a post in WordPress.

This answer on SO suggests that the first method is quicker to process, while the second method is quicker to write.

I also noticed that the first method is often mentioned in the Codex while the second method is mentioned on the_content filter page.

Is this only a matter of preference? Or does it come to performance and security too?

Thanks

1 Answer
1

There is no difference when you are using just echo. What works different is unset():

function test_unset_1()
{
    global $post;
    unset( $post );
}
function test_unset_2()
{
    unset( $GLOBALS['post'] );
}

test_unset_1();
echo $GLOBALS['post']->ID; // will work

test_unset_2();
echo $GLOBALS['post']->ID; // will fail

The reason is that unset() destroys just the local reference in the first case and the real global object in the second.

For readability use always $GLOBALS['post']. It is easier to see where the variable is coming from.

Leave a Reply

Your email address will not be published. Required fields are marked *