Brian Krausz

I build internet things

Obscure Wordpress Bug

December 29, 2008

While working on my new WordPress plugin (announcement post coming soon), I stumbled upon an interesting point in the way WordPress plugins work (well, Jorge stumbled upon it, I debugged it). Plugins are loaded as files in the global namespace, not within the confines of a function. This means that variables you declare can have an impact on the rest of WordPress.

A specific example: my plugin had the following lines of code:

foreach($custax_style_pages AS $page)
    add_action('admin_head-'.$page, 'custax_styles');

Harmless, right? Wrong! Unfortunately, the way WP parses queries includes this code:

for ($i=0; $ipublic_query_vars; $i += 1) {
    $wpvar = $this->public_query_vars[$i];
    if (isset($this->extra_query_vars[$wpvar]))
        $this->query_vars[$wpvar] = $this->extra_query_vars[$wpvar];
    elseif (isset($GLOBALS[$wpvar]))
        $this->query_vars[$wpvar] = $GLOBALS[$wpvar];
    //...
}

The end result is that, since $page gets registered in $GLOBALS, and “page” is common enough to be a query variable, everything goes to hell fairly quickly.

The moral of the story? Prefix your variables — all of them — unless you’re positive your code is encased in a function.

Share This Post