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

9th November 2023

MasterPress 1.3.10 is a feature and bugfix release. Workaround for fatal error introduced by changes to WordPress’ wpdb class in WordPress 6.4. Added actions to MPC files upload_field & WF image save_image functions.

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