WordPress: Introducing the functions directory

2 min read wordpress

If your WordPress functions file is anything like mine, it’s probably slammed full of helpful functions, actions and hooks… you’ve done your absolute best to comment and group relevant sections of code, but it still looks overwhelming.

I’ve had this problem for a while, I get horrible feelings in my brain every time I have to tackle the functions file. It’s a mess and difficult to maintain, no matter how you spin it. It’s not much better when other project contributors come along and have to deal with it, what happens they (or you) don’t understand where new code should go, it gets thrown haphazardly somewhere within the file.

To overcome this issue I’ve started to offload groups of code into new, specific files within what I call, the functions directory:

functions/
    admin.php
    content.php
    custom-post-types.php
    discussion.php
    fields.php
    hacks.php
    loader.php
functions.php
index.php
style.css

With this method code is easily split up into specific, manageable files. This negates the cluster fuck unorganised and cluttered nature of the functions file.

Loading these files…

To ensure these files are executed we can use the include statement to manually include each functions sub-file. However you might notice the functions/loader.php file, the purpose of this file is to discover any sibling .php files within the functions directory and include them automatically… that way you can quickly add a new file within the functions directory, say media.php, that file will be automatically included. Here’s what the loader.php file does:

<?php // functions/loader.php

// get the current path info
$function_path = pathinfo(__FILE__);

// loop through all php files within this functions directory...
foreach ( glob($function_path['dirname'] . '/*.php') as $file) {

// ... and if it's not loader.php, include it
if ( basename($file) !== 'loader.php' ) {
include $file;
}

}

And that’s the functions directory, a simple, effective stepping stone away from the beast that is, the functions file. I’ve put an example repo up on github for the functions directory for your forking pleasure.

If you have any tips / ideas / suggestions regarding this method or the general subject of the functions file, be sure to leave a comment below.