functions file, plugin, and theme scoping in wordpress mu
I've got a plugin that is declared and hooked following best practices described in this related question:
Wordpress: Accessing A Plugin's Function From A Theme
So it looks (platonically) like this:
if ( !class_exists( 'Foo' ) ) {
class Foo {
...
public function do_stuff() {
// does stuff
}
}
}
if ( class_exists( 'Foo' ) ) {
$MyFoo = new Foo();
}
Now, if I call $MyFoo->do_stuff() from a theme file, such as, say, single.php, $MyFoo in fact does_stuff and I see the output in the page.
However, if I write a function in functions.php that wants to call $MyFoo->do_stuff() and then call that function from single.php the object is not found. In summary,
Works:
in themes/my_theme/single.php:
if (isset($MyFoo))
$MyFoo->do_stuff();
Does not work:
in themes/my_theme/functions.php:
function do_some_foo_stuff() {
...
if (isset($MyFoo)) {
$MyFoo->do_stuff();
} else {
echo "no MyFoo set";
}
...
}
themes/my_theme/single.php:
if (isset($MyFoo))
do_some_foo_stuff();
Outputs -> "no MyFoo set"
This may be totally unsurprising, but it's something I need/want to work, so if anyone can explain what is going on it'd be appreciated. Why can't the theme's functions file (or other 开发者_JAVA百科plugin files in mu-plugins for that matter) find $MyFoo object?
Read up on variable scope. The variable $MyFoo
is not accessible within the function do_some_foo_stuff()
unless you declare it global first;
function do_some_foo_stuff()
{
global $MyFoo;
...
}
精彩评论