Content:
Coming up with variable names is not always the easiest task – you need something descriptive, that makes it clear what the variable holds.
If you have code to loop through a list of posts, you might write something like this
// Template code
$post_list = custom_post_query();
foreach ($post_list as $post) {
// output post data
}
// Rest of template code
Seems fine, right? We loop through a list of posts, with the $post variable referring to each individual record in the post list. $post will only exist inside the loop. And the variable name $post good – after all, that’s exactly what the data is.
Well, if you try this, you could end up with an unpleasant surprise – and one that’s difficult to debug.
The Global Variable
$post is actually a very important variable used by WordPress. You might never interact with it directly, and might not even be aware of its existence. But it’s there, and ready to bite if you’re not careful.
The default queries used by WordPress, whether to fetch posts or pages according to your site settings/hierarchy, output their post data to $post
, which is a global variable.
Calls to functions such as the_content()
, the_excerpt()
and the_title()
will use this global variable as a default data source, should no parameters be supplied to them.
What Actually Happens
Going back to our code, what we’re actually doing is inadvertently replacing the $post
global variable with the posts we’re looping through.
This means that any subsequent function calls that use $post
will be operating on the wrong data.
This can be made worse by the behaviour of other WordPress functions.
For example, running comments_template()
when the $post->id doesn’t exist will not prevent comments from showing. What happens instead is the function will show comments from all posts. If you don’t spot the incorrect comments, you might not notice anything is amiss.
The easy way to avoid these issues is to not is to prefix any variables you use, perhaps with something related to your theme name.
// Template code
$qb_post_list = custom_post_query();
foreach ($qb_post_list as $qb_post) {
// output post data
}
// Rest of template code
That way, you won’t inadvertently overwrite any of WordPress’ global variables.