January 07, 2014
Gotcha! Use Static Class Members in WordPress 3.0+ Themes

I recently came across an issue when I was writing a custom class to handle functionality in a WordPress theme that was instantiated in the functions.php file. Normally, this doesn’t present an issue; however, you’ll receive a Fatal error when trying to access methods of the object in a template that was loaded through the get_template_part() function (WordPress 3.0+). This is due to the variable scope limitation of the required template.

Fatal error: Call to a member function [method called] on a non-object in...

At this point you have 2 options: include the template file using one of PHP’s include/require method variations instead of through get_template_part(), or create static methods and properties inside of your class.  I prefer to go with the static approach even though there are some drawbacks including testing limitations, etc. All you need to do is load your class via an autoloader or include it in your theme’s functions.php file and call away!


NOTE: The static keyword is only available in PHP 5 and higher.

Copyright © 2022 Allan Kiezel – Long Island Web Designer & App Developer. All rights reserved.