Wordpress theme development and an interesting few techniques to employ in your theme development. So over the last few years I've been working on the odd project in wordpress. Some have meant the need for custom work becoming projects, such as my wordpress MVC library. It has helped me in numerous projects and hope it helps you. But my theme style has moved to an area where I wish to share and hope you like or can give any advice/tips on.

Table of contents

  1. Autoloading
    1. Folder Structure
    2. Naming Convention
    3. back to Autoloading
    4. Subfolders?
  2. Theme Class
    1. Static Calls
    2. Traits
  3. Wrapping Up

Autoloading

I saw an article that I agreed with that had kind of made me feel I was going in the right direction for a while, it was a smashing magazine article entitled: How To Use Autoloading And A Plugin Container In WordPress Plugins. Often in many other themes, I have seen a whole tonne of include and require calls to load in other files. What do I mean, like so: [php] include('inc/class_one.php'); include('inc/classTwo.php'); require('inc/Class1.php'); require('inc/subfolder/class_1.php'); [/php] Eventually as the codebase grows and more classes need to be added in then it can become quite huge e.g. ultra terrible example: [php] include('inc/class_one.php'); include('inc/classTwo.php'); require('inc/Class1.php'); require('inc/subfolder/classNine.php'); require('inc/subfolder/classTen.php'); require('inc/subfolder/classTen1.php'); require('inc/subfolder/classTen12.php'); require('inc/subfolder/subfolder/classOfHope.php'); require('inc/subfolder/subfolder/classOfHoping.php'); require('inc/subfolder/subfolder/anotherClass.php'); require('inc/subfolder/subfolder/AnotherBleedingClass.php'); require('inc/subfolder/subfolder/guessWhat.php'); require('inc/subfolder/subfolder_subfolder/AnotherClass.php'); require('inc/subfolder/subfolder_subfolder/Zeus.php'); require('inc/subfolder/subfolder_subfolder/Larry.php'); require('inc/subfolder/subfolder_subfolder/LarrysMate.php'); require('inc/subfolder/subfolder_subfolder/LarrysBrother.php'); require('inc/subfolder/subfolder_subfolder/LarrysMother.php'); [/php] Obviously this is silly! but it illustrates the problem of having to include many many lines of includes and requires to load in your code. The premise is to use autloading and namespacing to load in your classes, as and when you need them. Here is an example of the autoloader described in the article and what to use in your theme (yes I used my surname): [php] spl_autoload_register( 'QuinnAutoloader' ); function QuinnAutoloader( $class_name ) { if ( false !== strpos( $class_name, 'Quinn' ) ) { $classes_dir = realpath( plugin_dir_path( __FILE__ ) ) . DIRECTORY_SEPARATOR . 'core' . DIRECTORY_SEPARATOR; $class_file = str_replace( '\\', DIRECTORY_SEPARATOR, $class_name ) . '.php'; require_once $classes_dir . $class_file; } } [/php] Looking at the autoloader you may see that the str_replace function is looking for backslashes '\\'. It is only looking for one, the backslash character is just needing to be escaped before it is sent into the function.

Folder structure

You may also notice between the DIRECTORY_SEPARATOR keywords that their is a core string plonked in. This is where we are wishing to place our theme code in the theme folder. So our folder structure is going to look like this: folder-structure As you can see the place of our namespace for the theme is in a folder, which in this case is Quinn (yes, my surname again). Any other base namespaces/packages could also be loaded into here if you wish. But for Quinn we then have all our relevant theme files that we wish to load in.

Naming convention

So now we have our folder structure and we have our files but we need to know what is going to be the naming convention of classes. For Filenames and class names I adopted camel case so for example CoreClass.php would contain a class name of CoreClass. Base Namespaces are capitalised as is any sub folder within. This then gives a nice neatness to your folder structure and class calls.

back to Autoloading

The autoloader we are using is looking for namespaces to autoload. If you are unaware of namespaces then I suggest you read some great articles on the subject via google but one in particular that is good is dayle rees' article on the subject. So happy with that so far? No? well our namespacing is going to mean that we can load any file based on any namespace our code encounters throughout the functions.php file. You can add them as you go throughout the file or import them all at the top of the functions file. So for examples at top of function below the autoloader I may be wishing to import classes into my theme for use like so: [php] spl_autoload_register( 'QuinnAutoloader' ); function QuinnAutoloader( $class_name ) { if ( false !== strpos( $class_name, 'Quinn' ) ) { $classes_dir = realpath( plugin_dir_path( __FILE__ ) ) . DIRECTORY_SEPARATOR . 'core' . DIRECTORY_SEPARATOR; $class_file = str_replace( '\\', DIRECTORY_SEPARATOR, $class_name ) . '.php'; require_once $classes_dir . $class_file; } } use Quinn\Crud; use Quinn\View; use Quinn\CoreClass; use Quinn\QuinnTheme; [/php] Now this autoloader is going to be loading in files and classes based on the following premise. Using the first line above if I have a Crud class in the root of the Quinn folder, then within that file the top might look like this: [php] /** * Base class for CRUD operations * * @package Quinn * @subpackage Crud * @since 1.0.0 * @access private */ namespace Quinn; class Crud { ... } [/php] Notice I have declared a namesapce: [php] namespace Quinn; [/php] This needs to be the first line of code within the file. The autoloader is going to look at use Quinn\Crud and via the code within the autoloader include the file: core/Quinn/Crud.php Thus allowing you to call the crud class as per normal: [php] $crud = new Crud(); [/php] So now you no longer have to worry about a tonne of require and includes within your theme.

Subfolders?

So You also may have seen from the above image there was subfolders with the Quinn namespace folder. Yes indeed the autoloader can load the files within these subfolder too. However the namespace within these files must reflect the folder structure. So in the Quinn folder their was a Traits folder: subfolder-traits Using the Helpers.php file as an example then the top of the file would look like this: [php] /** * Helpers * * @package Quinn * @subpackage Traits * @since 1.0.0 * @access private */ namespace Quinn\Traits; class Traits { ... } [/php] Notice the namespace reflects the folder structure but in namespacing format [php] namespace Quinn\Traits; [/php] So that is how you load in subfolders and ensure the namespaces allow your autoloader to work nicely. Now you may have noticed the folder name was traits, this will be written about later in the article as to how to make calls throughout the theme.

Theme Class

So by theme Class I mean in how to group all these classes into one class that can be loaded. I have been looking at few ways to incorporate a container class but so far I use a ThemeClass that can call other classes into it. The ThemeClass is a singleston when instantiated so as not to call any hooks/filters more than once e.g. [php] class QuinnTheme extends CoreClass { /** * Constructor. * * @access public */ public function __construct() { parent::__construct(); } /** * init method. * * @access public */ public function init() { add_action( 'init', array( $this, 'init_theme' ) ); } } $QuinnTheme = QuinnTheme::get_instance(); [/php] the CoreClass get_instance() method is like so: [php] public static function get_instance() { $c = get_called_class(); if ( !isset( self::$instance[$c] ) ) { self::$instance[$c] = new $c(); self::$instance[$c]->init(); // call init bub } return self::$instance[$c]; } [/php] So once the theme is instantiated all hooks and filters can be called within the init() method. Quick Note: you may have noticed the methods are using underscores within the names, which is going against all our previous conventions. You are correct! This is a wordpress convention I pull in to follow and you will see what I mean with examplese later on with wordpress' default function calls Now you have the $QuinnTheme object that can be used within theme template files but I find that within wordpress you have to globalise variables before using them. So within header.php If I wanted to run a method I would need to use global to pull in the variable like so: [php] // header.php global $QuinnTheme; $QuinnTheme->sub_method(): [/php] Now this is ok if you are happy to use that global but I break my theme's up into multiple partial files and pull them all in and having to add that global line into ever single one started to bug me. I did find a way around it.

Static Calls

Static calls allow you to step around this. First you need to update any functions/methods you wish to become static. Simply add the static keyword into your code: [php] public static function sub_method(){ // code here } [/php] You can simply then throughout your theme just use the class name itself and the static method: [php] // header.php QuinnTheme::sub_method(): [/php] So this gives you some nice ways to call code throughout your theme. Now you may end up with lots of these static function calls in your main ThemeClass and we try our best to reduce a classes bloat and size if possible. So by reduction we must move these calls into other relevant classes or clumps of code. We could use classes if that is what is needed. I have found that a lot of the static calls can be nicely placed into traits.

Traits

Traits are a great way to import functionality into another class, their is no need for inheritance, just pull in a trait and its code is pulled into the class and can be used. I have another post more in depth about traits, which you can read here. But a quick sum up, you can create a trait like a class but instead use the trait keyword. If you wish to Follow PSR-2, add the word trait to the traits name: [php] trait CommonStuffTrait { public function getIdea(){ return 'the awesome idea'; } } [/php] And then to import this trait into your class: [php] class Model { use CommonStuffTrait; } [/php] So if we have a lot of method calls about a user on the front end then we could group these static calls into a UserTrait and then import it into our main class. Remember this would be in the traits folder and thus its namespace would need to be defined as such. [php] namespace Quinn\Traits; trait UserTrait { public static function getName(){ echo 'the name'; } public static function getEmail(){ echo 'email@email.com'; } public static function getTwitter(){ echo 'twitterhandle'; } public static function getReligion(){ echo 'the awesome'; } } [/php] then import it and use it in your class [php] use Quinn\Traits\UserTrait; class QuinnTheme extends CoreClass { use UserTrait; /** * Constructor. * * @access public */ public function __construct() { parent::__construct(); } /** * init method. * * @access public */ public function init() { add_action( 'init', array( $this, 'init_theme' ) ); } } $QuinnTheme = QuinnTheme::get_instance(); [/php] And then those calls can be called in any theme file like so: [php] QuinnTheme::getReligion(); // the awesome [/php] Your files can then be split up into more relevant names that describe what they are doing. Your traits folder can have trait names such as:
  • SocialTrait
  • MetaTrait
  • MobileTrait
  • HelperTrait
It potentially could become overkill in how many files but it gives you a good way to group your code into relevant blocks that can then be imported into your main class. One pitfall is unless you are using something like phpstorm, finding the static method calls within traits can be difficult to find. Of course Atom and sublime come with the handy text word finder shortcut and will then find the file that line of text is in. It is also to note not to go grouping absolutely everything into traits, this is not an article to say to do so but instead to give you information on how traits can aid your wordpress theme development.

Conclusion

Well I hope that has been an interesting read and if you are using wordpress you find any help and use in this article. If not good day to you. Any questions please get in touch. thanks for reading you beautiful people

Monthly Archives: September 2015

WordPress theme development

WordPress theme development and an interesting few techniques to employ in your theme development. So over the last few years I’ve been working on the odd project in wordpress. Some have meant the need for custom work becoming projects, such as my wordpress MVC library. It has helped me in numerous projects and hope it

Read more