2
Posted July 8, 2012 by Spyros in PHP Programming
 
 

How to Design a WordPress Theme From Scratch in a Model View Controller Design Pattern

wordpress-plugins-600x300
wordpress-plugins-600x300

I’ve always been interested in web programming and have done quite a lot of it both in backend(mainly) but in frontend as well. One of the large projects I’ve done in the past was to create my own WordPress theme from scratch. To start this project, I first had to take a look at how people were actually coding WordPress themes at the time, in order to discover techniques and ideas. There was a particular thing that was mind boggling at the time though. As in many PHP projects, people tend to mix PHP tags along with HTML code, mysql calls, even Javascript.

There are many people who would argue that this is probably a good enough way to do things, but it’s undoubtedly very difficult to maintain such code and reuse it in other WordPress projects. Take a look at this example code from a very well known open source WordPress template :


<?php
    }

    // if we have widgets in the 'Mandigo Bottom' sidebar
    if ($sidebars_widgets[$index_mandigo_bottom]) {
?>

        <ul class="inline-widgets">
            <?php dynamic_sidebar('Mandigo Bottom'); ?>
        </ul>

<?php
    }
?>
</td>

<?php

This kind of code is obviously not ideal, there is much room for improvement. Of course, the functionality of the code is fine, the user will be noticing no problems whatsoever, but the programmer or programmers who are into coding this, will be having a nightmare if they ever need to change something 3 months later. In short words, this code is not maintainable.

Using a Template Manager, Wouldn’t That be Too Slow ?

This situation clearly calls for a template management system and a better handling of code using classes and objects. There are people who argue that template engines like Smarty and the likes are rather slow. This is actually correct, but I feel it’s worth it anyway. The difference in loading is not noticeable and the advantages in overall code design are tremendous. However, I understand that people are looking for the fastest solutions. For this matter, I have mentioned that I am personally using a great template system in my project, which is custom made and very very fast. I highly advice that you take a look at that and start using it in your projects as well. For now, let’s see how it works with WordPress template design.

How to Use the Template Engine and Organize Your Code in Responsible Classes

The first thing to do, of course, is to include the actual template engine file in your functions.php file. This is how I do it :


define('THEME_PATH', TEMPLATEPATH . '/');
define('TEMPLATES_PATH', TEMPLATEPATH . '/templates/');
define('CLASSES_PATH', TEMPLATEPATH . '/classes/');
define('LIBRARIES_PATH', TEMPLATEPATH . '/libraries/');

/* Include Template Engine */
include LIBRARIES_PATH . 'template_engine/template_engine.php';

Notice that i define some important constants here, that are going to be used throughout my WordPress theme. In my classes folder, i have what are called Models in an MVC pattern. I have a Post class, a MetaBox class, a Portfolio class and so on. Let’s take a look at a very small class example, a basic implementation of my Image class :


<?php

class Image {

public function timthumb($src, $width, $height, $crop = 0)
{
     $timthumb_path = LIBRARIES_URI . 'timthumb/timthumb.php';
     $options = "?src=$src&w=$width&h=$height&zc=$crop";

     return $timthumb_path . $options;
}

}

?>

This is simply utilizing a timthumb method, that actually uses the well known timthumb library to resize images. You can see that when I want to use that, I will do something like  that in my template files, after i initialize an $img_class object :


<img src = "<?=$img_class->timthumb($blog_image[0], 530, 230);?>" alt = '<? the_title(); ?>' />

But how exactly do i get that $img_class object ? This is where controllers come into play. Normally in a WordPress theme, there are some predefined files that we have to use. For instance, when we want to create the single post template, we need to create single.php and do our magic in there. In most, if not all themes, they again tend to put everything in there, from PHP code to mysql queries. I do it differently though, let’s take a look at my single.php, which is actually the controller of the single.tpl.php file (I removed code to make it easier for this example) :


<?php

	require_once CLASSES_PATH . 'post_class.php';
	require_once CLASSES_PATH . 'image_class.php';

	$tpl = & new Template(TEMPLATES_PATH);

	$post_class = new Post();
	$img_class = new Image();

	$post_id = $post->ID;
	$has_sidebar = get_post_meta($post_id, 'meta_select_sidebar', true);

	$has_breadcrumbs = $post_class->get_breadcrumbs($post_id);
    $tpl->set('has_breadcrumbs', $has_breadcrumbs);

	$tpl->set('has_sidebar', $has_sidebar);
	$tpl->set('page_width', $post_class->get_page_width_meta($post_id, $has_sidebar));
	$tpl->set('post', $post);

	$author_id = $post->post_author;
	$author = get_userdata($author_id);
	$tpl->set('author', $author);

	$tpl->set('img_class', $img_class);

	echo $tpl->fetch('single.tpl.php');

?>

Notice how clean that looks and how easy it is for the programmer to understand what it is. It just includes two models, the post and the image model and gets information using their methods. It retrieves a sidebar, if there is any, possible breadcrumbs, gets page width, author information and so on. Very easy to read and change, isn’t it ? It then sets variables to be used with our template system. For instance, it sets a has_breadcrumbs variable, based on the “$post_class->get_breadcrumbs($post_id);” method, which actually retrieved this information from the model. Now, in our template file we no longer need to mix PHP, HTML and more. We just write HTML and include simple variables or control structures, that make our code very readable. Let’s take a look at a small part of my single.tpl.php file and see how the breadcrumbs variable is used :


	<div id='content' class='center'>

		<div id='middleContent' class='<? echo $page_width; ?>'>

			<?php if ( $has_breadcrumbs == 'yes' ): ?>
				<?php if ( function_exists( 'breadcrumbs_plus' ) ) breadcrumbs_plus( array( 'singular_post_taxonomy' => 'category' ) ); ?>
			<?php endif; ?>
                 ........
         </div>
                 ........
   </div>

Look how well defined our code is now. We can easily determine which thing belongs where, edit and extend our code. Notice that we are also using the php control structures in verbose format, like described here by PHP docs.

Hope that helps you and gives some nice insight into creating your WordPress themes in a method that will save you from feature headaches and is just so beautiful that cannot be easily ignored.


Spyros