applying oop to wordpress themes

first couple of wordpress themes people hack together are unmaintainable pieces of junk, so was mine (to say the least).

the problem usually lies in the custom functions.php file, in which all things evil mostly takes place. the code in this file is generally just sequentially executed crap which, if you’re lucky, won’t collide with any core wp functionality or the badly written plugins you install.

plus – variables from functions.php can’t be accessed in header/sidebar/footer files unless you declare every single one of these functions as global. which is a pain.

luckily the solution as simple as elegant. wrap your custom functionality in classes! for most themes one class is enough. i won’t go into detail about how oop works in php5, there is plenty of stuff written on that subject already. but here’s how to apply it to theme development!

inside your functions.php, create a new class:

class YourTheme{
	public function __construct(){
		$this->some_variable_youll_need_throughout_the_theme = "random string, could be an array or anything else";
	}
	public function get_some_var(){
		echo $this->some_variable_youll_need_throughout_the_theme;
	}
}
$YourTheme = new YourTheme;

now, inside any theme file you can access this class by adding this to the top of the file:

global $YourTheme;

then, access all methods and variables this way:

$YourTheme->get_some_var();

You can also set variables really simple, just the way you would expect:

$YourTheme->another_var = "h3ll0 w0r1d";

and retrieve it in another theme file:

echo $YourTheme->another_var;

that’s how simple it is. have fun.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>