Variable names in WordPress (or why you should never use $category as a variable name)

The great thing about WordPress and PHP is that you can call variables anything you like. The bad thing about WordPress and PHP is that you can call variables anything you like…

Think about these variables:

$post, $category, $template

What do they have in common? Well, they all look like good, descriptive variable names don’t they? What if you changed this to

global $post, $category, $template;

and then put this in a template for a post…?

echo $post; echo $category; echo $template;

Well, you’d get all sorts of interesting things, as $post, $category and $template are all global variables in WordPress.

FYI: there is a (partial) list of WordPress global variables in the Codex.

So if you use these variable names, and you also access global variables with those names… sometimes you’ll be thinking: why doesn’t my code work? And you’ll find out that when you thought you were changing a local variable you were actually changing a global variable, and that affected something else…

See also: Global variables and understanding scope in WordPress.