Globalizing $wf

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.

Latest From the Blog

MasterPress 1.1.4 now available

MasterPress 1.1.4 is now available. This release contains an important compatibility fix for WordPress 4.5 to allow correct detection of the taxonomy term editing screen. Without this fix, any custom fields you have attached to custom taxonomies will not be shown at all in the editing form. Note also that MasterPress will still detect the edit screen correctly in… 

Plugin Requirements

MasterPress requires a minimum of WordPress version 3.4, MySQL 5, and PHP version 5.2.4.

We also recommend that PHP is configured to use a memory limit of 64MB per request (128MB may be required for sites with higher complexity).

This plug-in is not compatible with the hosted service.