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.4.1 is now available

27th May 2024

This update addresses backwards compatibility issues that were introduced in the previous update. There were some edge cases where PHP 7 had issues and it didn’t work at all on PHP 5.6.We have now changed it so that the PHP 8 compatibility changes will now only affect PHP 8 and will be more thorough with… 

Plugin Requirements

MasterPress requires a minimum of WordPress version 4.9, MySQL 5.6, and PHP version 5.6.20.

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 WordPress.com hosted service.

Three AM