January 16, 2015

Manage your “functions.php” file using includes

If you’re trying to come up with a crazy complex WordPress site, including custom taxonomies and custom post types, and all sorts of non-standard, very involved PHP functions your ‘functions.php’ file can get quite messy. And if you make even minor mistakes in this file you run the risk of taking your whole site down. (assuming you’re working live, like an idiot).

So, if you’re like me, and your style of programming is akin to throwing feces at a computer screen to see what sticks, then trying to clean up your messes later; it’s advantageous to sequester your experimental code, so it can be modularly removed from your site in a pinch if you just can’t seem to find that illusive hard return that’s causing the dreaded “header” error.

So I’ve been organizing all my complex or needlessly complex code into individual files in an “includes” folder in my theme’s main directory. You can then access these files quickly and easily in your ‘functions.php’ file by using the ‘require’ method like this:

[pastacode lang=”php” message=”Adding includes to ‘functions.php’ file” highlight=”” provider=”manual”]

<?php require_once('includes/your-file.php'); ?>


This opens up the opportunity to reuse functions efficiently, and easily comment out code that might have stopped working due to your lack of sleep and co-ordination when typing semi-colons. Like this:

[pastacode lang=”php” message=”Use multiple includes in a function for efficiency” highlight=”” provider=”manual”]

function codex_custom_init() {


In the example above I’m using a function to register multiple custom post types. If I want to remove any of these post types temporarily, all I have to do is comment out their individual line.