Just about every interaction with the MasterPress API originates from the global $wf object, which is a global singleton instance of the MEOW class. The PHP language has one particular quirk that can often trap developers – the need to declare a variable as part of the global scope within the body of functions, and in any code that might execute in the context of a function.
If you start to rely on the MasterPress API a lot, and hence the $wf object, you’ll inevitably run into this problem. Consider the following code, which is an example implementation for a shortcode handler to bring code examples into post bodies:
Example 1: Shortcode example with a problem.
Nothing looks out of place in this code, but as soon as an example shortcode is processed, you’ll have a fatal error on your hands. If you enable WP_DEBUG you’ll see a string of errors like this:
Notice: Undefined variable: wf in /path/to/your/site/wp-content/themes/your-theme/functions.php on line 460 Notice: Trying to get property of non-object in /path/to/your/site/wp-content/themes/your-theme/functions.php on line 460 Notice: Trying to get property of non-object in /path/to/your/site/wp-content/themes/your-theme/functions.php on line 460 Fatal error: Call to a member function exists() on a non-object in /path/to/your/site/wp-content/themes/your-theme/functions.php on line 462
The fix for this is easy – a single line at the top of the function:
Example 2: The global declaration
Now your code can see the $wf object, and everything should be working fine again.
IMPORTANT: Use global at the top of partial templates too!
Partial templates are brought into your templates as if they are inside a function body, so the you should add the global declaration at an early point in these templates, as in the header.php example below:
Example 3: Adding global to partial templates
Please refer to $wf – the point of entry into the entire API for more information. Also, if you’re not familiar with the particulars of variable scope in PHP, review the Variable Scope page in the PHP manual.