I provide a free public Github repository containing example code for starting work on a WordPress theme which uses PHP namespaces and template parts.
Hot on the heels of the base code for WordPress plugins I wrote about earlier, comes an update for the equivalent reference code for a WordPress theme using PHP namespaces. The idea is the same: use the code as a starting point for developing your own WordPress theme, and take advantage of technology available on servers running more up-to-date versions of PHP.
The first question which many theme developers will ask is, “why not just use Underscores?” (Underscores is the great theme starter tool from Automattic, which also allows you to download a codebase upon which you can build a theme.)
The code in Underscores is good and it uses many of the same principles which power WordPress core. In fact, many people who work on WordPress core also work on Underscores. It’s a great starting point if you don’t have a lot of coding experience, or of you want to adhere to the sensible guidelines set out by WordPress core and stick closely to the core principles.
For the experienced developer, the code in Underscores suffers a little because it has to support legacy installations in the same way that WordPress core does. It uses functions in the global scope instead of PHP namespaces and so it can’t benefit from the advantages which a class-based structure brings.
The functions in the global scope are always loaded and defined, even if they aren’t used, which can quickly bring memory and performance issues unless the developer takes special care to address this. Using PHP classes, loaded correctly if and when they are needed, often leads to less memory usage per request or per process. This, in turn, makes the code work more quickly.
The code I use, which you can get from this public GitHub repository, is a starting point from which you can build your own themes. You can separate out individual blocks of functionality into different classes – for example theme option registration, taxonomy handling, media handling – and load them individually. The base code also gives you a direct example of how to use template parts and WordPress’ own
get_template_part fallback principle, so that you can build your theme in a modular way.
Feedback and comments are most welcome: the code and instructions are at https://github.com/markhowellsmead/wp-theme-default.