Chapter 6
Themes

Well-designed content management systems seek to create a separation between design, content, and functionality, and WordPress is no exception. So far in this book, we’ve covered the fundamental building blocks of WordPress that primarily manage functionality: The Loop, post types, and plugins. Themes, on the other hand, comprise the structural CSS, HTML, and JavaScript code that handle the overall design, layout, and visual user experience of a website. In other words, themes are all about making your website look really good, and less about the programming that does all the heavy lifting in the background. There are plenty of considerations that muddy these waters, though, as we’ll learn later in the chapter, but for the time being, let’s focus on the basics of what goes into a theme.

Basic Components of a Theme

At their core, themes are really nothing more than the HTML code to create a structure that describes where different components will live on a website, and the CSS code that describes what those components will look like. For the purposes of this chapter, we’ll assume you have a solid understanding of both HTML and CSS, and that you understand the fundamental components necessary to construct a successful web page. It’s vital that you understand how all those pieces work together within a WordPress theme.

Just like with plugins, WordPress provides us with a standardized place to store our themes within a particular WordPress installation: the wp-content/themes directory. Although only one theme can be activated at any given time, WordPress does let you store as many themes as you like to activate and deactivate at your leisure. Keeping with the same pattern we saw with plugins, themes must have unique names and be stored in their own unique directories within the wp-content/themes directory. So far, so good.

Required Elements of a Theme

Now that we know where to save the files within our theme, we need to start building those files. While we’ll probably end up creating several more files, we technically only require two files to set up a valid theme:

  • styles.css

  • index.php

The styles.css file is the more crucial of the two, and is the first file that WordPress will look for when it gathers information about your theme prior to activation. Similar to the way in which it recognizes plugins, WordPress searches for a standardized header at the very top of the styles.css file to gather pertinent information about your theme. Since we won’t be creating our own full-blown theme here within this chapter, let’s take a look at how the team over at WordPress.org has done it with their latest and greatest theme, Twenty Eleven:

chapter_06/twenty-eleven-styles-header.php
/*
Theme Name: Twenty Eleven
Theme URI: http://wordpress.org/extend/themes/twentyeleven
Author: the WordPress team
Author URI: http://wordpress.org/
Description: The 2011 theme for WordPress is sophisticated, lightweight, and 
  adaptable. Make it yours with a custom menu, header image, and background -- 
  then go further with available theme options for light or dark color scheme, 
  custom link colors, and three layout choices. Twenty Eleven comes equipped 
  with a Showcase page template that transforms your front page into a showcase 
  to show off your best content, widget support galore (sidebar, three footer 
  areas, and a Showcase page widget area), and a custom "Ephemera" widget to 
  display your Aside, Link, Quote, or Status posts. Included are styles for 
  print and for the admin editor, support for featured images (as custom header
  images on posts and pages and as large images on featured "sticky" posts), and 
  special styles for six different post formats.
Version: 1.0
License: GNU General Public License
License URI: license.txt
Tags: dark, light, white, black, gray, one-column, two-columns, left-sidebar,
  right-sidebar, fixed-width, flexible-width, custom-background, custom-colors,
  custom-header, custom-menu, editor-style, featured-image-header, 
  featured-images, full-width-template, microformats, post-formats, 
  rtl-language-support, sticky-post, theme-options, translation-ready
*/

As you can see, this is fairly standard fare. What’s important to remember is that no two themes loaded in the same WordPress installation can have the same name; so if you are building a theme by copying an existing theme and making modifications from there, make sure you change the header information here to your own unique values.

The remainder of the styles.css file is just standard CSS. You can use it to create all the cool styles you’ll utilize to make your theme look awesome.

The index.php file, on the other hand, is the initial page that a browser will fire upon visiting your site, and serves as the key file to describe the layout of the main page (and potentially the entire site, as we’ll discuss in a moment). We can place whatever HTML we want our theme to display inside this file, but since our goal here is to output our WordPress content via our theme, we’ll take a more structured approach. Let’s take a look at a stripped down index.php file we might commonly see in a theme:

chapter_06/basic-index.php
<?php

// Insert the header.php file to begin the page output
get_header();

// Add in page logic via the Loop
if (have_posts()) :
   while (have_posts()) :
      the_post();
      the_content();
   endwhile;
endif;

// Insert the sidebar.php file to include widgetized sidebars
get_sidebar();

// Insert the footer.php file to complete the page output
get_footer(); 

?>

Right away, you’ll notice that this index.php file is broken up into four sections:

  • header area

  • the location to add The Loop, which will define our page logic

  • sidebar area

  • footer area

Just by looking at the comments in the code, we can deduce that get_header() grabs and inserts the header.php file, while get_sidebar() and get_footer() perform the same function with sidebar.php and footer.php, respectively. Fairly easy, right? There’s no need to define the specific names of those files; WordPress assumes that you’ll follow its nomenclature (a recurring theme, as we’ll see here in a moment). We’ve already covered The Loop in detail in Chapter 3, so we should already be able to see where the content is going to be added. However, this does introduce three more files that we’ll need to add to our theme:

  • header.php

  • sidebar.php

  • footer.php

These files aren’t vital, but you’ll find almost every theme makes use of them. And just to keep you on your toes, they won’t necessarily include what you think they might if you try to interpret them literally. For instance, the header.php file will contain all the display code required to create the code of a given page right up to where the content code is added into the outputted source code. This includes the <DOCTYPE> information for your outputted page, all the typical components you’d need in any <head> code such as meta information and links to your stylesheets, and the opening <body> tag to begin your display code. With all that said, there are two tasks you must include when creating your header.php file that will break WordPress without their presence:

  • Reference the styles.css file you’ve set up to initialize your theme.

  • Add the wp_head() function in the <head> code to initialize WordPress and ensure that all core functions work properly.

Similarly, the footer.php file can cover all the outputted source code from the bottom of the content block to the end of the file, although, in our example, we’ve inserted our sidebar.php file in this space, which serves to include logic for our widgetized areas. Typically, the footer contains the </body> and </html> tags, and must contain wp_footer() to allow core WordPress functions to manage footer settings as required; without it, unexpected results will occur when WordPress uses your theme.

Note: Tying It All Together

If you were paying close attention in Chapter 5, you’ll recall that two of our most common action hooks were the wp_head and wp_footer action hooks. The functions that we’ve just discussed above—wp_head() and wp_footer()—are the functions that actually trigger each of these action hooks, respectively. Nothing like tying it together with a nice little bow, right?

Let’s stop for a moment and draw an analogy to illustrate this point further, using a hamburger (or a veggie burger if you prefer) as an example. Now, the way that we prefer our burgers may well be different from the way you prefer yours. While a lot of people prefer to put their pickles, mustard, and ketchup underneath the meat, with the cheese, lettuce, and tomato on top, we choose to have nothing underneath our burger, instead having all toppings between the meat and the top bun. Other people may choose to skip the mustard and ketchup, favoring mayonnaise as their only condiment. Whatever your preference, what we all have in common on our burger is the fact that there’s a top bun, a bottom bun, and the meat in the middle—what you add to the burger is really up to you.

In the same way, themes are really all about visual flavors and preferences. We all have stuff on the top (a header), stuff on the bottom (a footer), and meat in the middle (the content being added by The Loop). Other than that, as designers we like to be creative and make our themes uniquely our own, much like we do when we prepare our burgers. Consider Figure 6.1.

index.php structure dressed up like a hamburger hamburger analogy themes as hamburgers index.php file theme configuration

Figure 6.1.  index.php structure dressed up like a hamburger

What the burger-maker has done here is change the very nature of the meal. It’s no longer a hamburger, but a double cheeseburger, and we’ll need to manage some options that deal with the cheese. Bringing the analogy back to the index.php file within our theme, we’ll call these places where we need to manage options sidebars, and we can move them around however we like. In our initial example, we’d already added one sidebar between The Loop and the footer, but now we have to manage two sidebars that may have different options. The easiest way to do this is to create a left and a right sidebar, which we can do by passing the correct standard parameter to the get_sidebar() function, as is done in the revised example:

chapter_06/dual-sidebar-index.php
<?php

// Insert the header.php file to begin the page output
get_header();

// Add in page logic via The Loop
if (have_posts()) :
  while (have_posts()) :
    the_post();
    the_content();
  endwhile;
endif;

// Insert both widgetized sidebars
get_sidebar('left'),
get_sidebar('right'),

// Insert the footer.php file to complete the page output
get_footer(); 

?>

We’re cooking with gas now, except … wait. We’ve added two sidebars to our theme, but we only have one sidebar.php file. What gives?

Easy—get_sidebar() takes one optional parameter, a name that corresponds directly to a standard nomenclature with sidebar.php. So when you use get_sidebar('left'), get_sidebar('right'), or even get_sidebar('footer'), WordPress will seek out sidebar_left.php, sidebar_right.php, or sidebar_footer.php, respectively. Nomenclature, in fact, plays a very big role in determining how WordPress parses out template files within your theme, as we are about to find out.

Nomenclature Hierarchy and Page Templates

We now have a handle on the fundamental components you can use to assemble your web pages within your WordPress theme. This is great, but what about extending those styles and changing your theme depending on where you are in your website? After all, it’s quite common to make your home page appear different from your internal pages, and you just might want to have a distinct look for a 404 page that pops up when a user tries to visit a place on your site that doesn’t actually exist. Regardless, WordPress has you covered in two ways:

  • the template nomenclature hierarchy

  • page templates

Let’s tackle the nomenclature hierarchy first.

By default, WordPress requires that you only create one template file within your theme: index.php. If you create no other template files aside from index.php, WordPress will simply default to this visual styling for everything it needs to display on your website. However, WordPress provides us with a specific nomenclature system that provides a handy way for theme designers to automatically display templates for a particular type of page output, or even for a page, post, or category. All you need to do is make a copy of your index.php file, rename it to match up with the type of content you’ll display, and then make your template modifications within that file. Consider the WordPress Template Hierarchy in Figure 6.2.

A simplified version of the WordPress template hierarchy structure nomenclature hierarchy themes templates nomenclature hierarchy

Figure 6.2. A simplified version of the WordPress template hierarchy structure

This simplified hierarchy structure describes the process; it helps to think of it like a funnel, with a URL working top-down through the hierarchy. At the top of the structure, there are templates used to describe the most specific forms of content types we could have. If a template file exists for a specific slug or post ID, that template is used. If no slug or ID template file exists, WordPress would look for the next template file in the linear hierarchy and use the first available, defaulting to index.php if no file is found until that point.

For example, let’s say that you would like to create a page template to manage the appearance of all your pages, but you’d like to give your About Us page its own look and feel. You could accomplish this by creating a template named page.php to handle all the pages within your theme, but then create a second file named page-about.php with the specialized display logic (assuming that “about” is the slug for that particular page).

The most common templates modified by theme designers, aside from index.php, are colored in blue in Figure 6.2. Here’s what each of them modify:

  • single.php manages all display formatting for individual posts

  • page.php manages all display formatting for individual pages

  • home.php manages all display formatting for the home page (called from the is_home() function, rather than the is_front_page() function, which is managed by the front-page.php display template)

  • archive.php manages all display formatting for post-listing pages (those that typically display post excerpts)

  • 404.php manages all display formatting for any pages not found (this can be useful for improving your visitors’ experience by giving them helpful navigation tips, since you can safely deduce that they’re experiencing what they didn’t expect on your site)

Note: But Wait—There’s More

Figure 6.2 lists only some of the most common page template types used by theme designers. For a more complete listing, have a look at the diagram provided by WordPress.

The archive.php template is its own special case as well, as it is the root controlling template file for a variety of templates, including categories, tags, and several others such as taxonomies, which aren’t pictured here. Other than this, the archive.php template works just like the others. For example, let’s say that you’re running a sports website about the Olympics, and you have a particular interest in swimming events. Working from the bottom up, you could create a specialized display template for posts about Olympic swimming by creating a file called category-swimming.php. However, you may also want to post about sports unrelated to swimming that have no need for a distinct appearance, so you could create a second template called category.php that serves this catch-all category. Finally, since you’ll be doing this over the course of several Olympic Games, you may want to display older, less relevant posts differently; you could then use another display template for archived posts. Shockingly, this would be named archive.php!

Page Templates

The other way to create distinct layouts in WordPress is to use page templates. It’s no surprise to find that you can only use page templates with individual pages, but they’re useful for giving your end user an easy way to change the appearance of a page within the page editing screen.

Creating a new page template is easy as pie. Just copy an existing template you have within your theme and give it a unique name. There’s no requirement to follow a nomenclature for filenames of page templates as it is with the template hierarchy; in fact, you’ll want to make sure that you avoid naming your page templates one of the template names, as it will cause it to behave in a way you don’t want. Instead, you register your page templates with WordPress in what should now be a very familiar way: having a standardized comment format at the top of your template file, as described here:

chapter_06/page-template-registration.php
<?php
/*
Template Name: Antelope General Special Sales Page Template
*/
?>

As the required Template Name: label suggests, the name of your custom page template is defined here, and once saved, you’ll find it immediately in the page templates drop-down on your page editing screen. Nothing to it, as Figure 6.3 shows.

Page Templates dialog box pages formatting page templates themes page templates

Figure 6.3. Page Templates dialog box

Adding Functionality to Your Theme

So far, we’ve talked in detail about how themes work and are structured, which is all well and good, but sooner or later you’ll want to make your theme sing and dance, and that means adding some theme-specific functionality. For this reason, an important file that you’ll find in most themes is the functions.php file. A file that WordPress automatically searches for when it loads a theme, functions.php is essentially treated as a theme-specific plugin. There are plenty of appropriate uses for it (and inappropriate uses, as we’ll discuss in a bit); what’s important to remember is that functions.php is where you’ll want to place custom PHP functions that make sense to use within the context of your theme, and your theme alone. Let’s take a look at some of the more common uses of functions.php.

Tip: Keep It Functional

Functions defined and written into functions.php are automatically loaded whenever the theme is in use; therefore, it’s useful to keep in mind that long, unwieldy functions.php files can actually slow your website down.

Adding Custom Menus

While you can literally add any functions you’d like to the functions.php file, one of the most common functions theme designers use involve setting up custom menus for extended navigation on the site. WordPress gives us an exceptionally easy method for creating as many menus as we’d like, which is useful for producing top header menus, footer menus, contextual menus, and any other type you can dream up. In order to create our menus, we’ll need to register them within our functions.php file using the register_nav_menus() function, which takes an array of menu slugs and descriptive names as its argument. Let’s have a look at it in use:

chapter_06/functions-php-menus.php
<?php

if ( function_exists( 'register_nav_menus' ) ) {
     register_nav_menus(
       array(
        'header_menu' => 'Header Menu',
        'footer_menu' => 'Footer Menu',
        'mobile_menu' => 'Mobile Menu'
       )
     );
}

As is fairly plain to see, we’ve registered the availability of three new menu files in this example—a header menu, a footer menu, and a mobile menu. With this code saved to our functions.php, we’ll now have these menu options available to us when we navigate to the Menus screen in the Dashboard at Appearance > Menus; here we can make modifications to our heart’s content. However, we still need to place them in our theme, and to do this we need only use the wp_nav_menu() function in the desired location within our theme, which looks like this in action:

<?php wp_nav_menu('header_menu'), ?> 

Important: Working Backwards

The custom WordPress menu system was introduced in WordPress 3.0. If you want to make sure that your theme is compatible with WordPress versions older than 3.0, use the conditional if ( function_exists ( ‘register_nav_menus()’ ) code as described in our recent example.

Tip: Choose Your Format

While the standard usage of wp_nav_menu() is fairly basic, you can do all sorts of formatting tricks with it. Have a look in the WordPress Codex for the range of parameters you can pass to the function to extend your custom menus.

Creating Widgetized Areas

Aside from adding customized menus, functions.php is often utilized to extend WordPress’s functionality, creating additional widget-ready areas for use within your theme. Consider the following code:

chapter_06/register-widgetized-area.php
<?php

// Register Antelope Featured Widgetized Area so it exists and we can use it
if ( function_exists('register_sidebar') )
register_sidebar(array(
  'name' => 'Antelope Featured Widgetized Area',
  'before_widget' => '',
  'after_widget' => '',
  'before_title' => '<h2>',
  'after_title' => '</h2>',
));

?>

Nothing to this, really. Here, we’re just letting WordPress know that we have a new widgetized area called Antelope Featured Widgetized Area that we’ll want to use. WordPress will respond by creating a namespace for you to work with; so now when you go to the Appearance > Widgets area within the admin area, you’ll see a new sidebar named Antelope Featured Widgetized Area. Go ahead and fill it up with whatever widget functionality you’d like, and then we’ll move on to the next (and final) step so that we can actually reap the benefits of our efforts.

Since we’ve just registered a new widgetized area, let’s follow through and add it to our theme in a useful location for our purposes. Widgetized areas can be added anywhere in a theme, but they’re commonly added within sidebar.php templates (or derivatives thereof). Just locate the place in your code where you want to add your new widgetized area, and drop in the following PHP code:

chapter_06/display-widgetized-area.php
<?php 

// Output Antelope Featured Widgetized Area in our theme
if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar↵
  ("Antelope Featured Widgetized Area") ) : ?>

<!-- Default formatting code here  -->

<?php endif; ?>

We promised we’d avoid delving too deeply into PHP here, but this shouldn’t be too scary. Here we are just being responsible and making sure that our theme has no issues; for example, if the theme is unable to find either the dynamic_sidebar function (highly unlikely, as it’s a core function) or the widgetized area we just registered in our functions.php file (more likely, since everybody is prone to human error). In the event that the theme runs into an issue here, it’ll just display the output code we’ve specified—in this case, a descriptive comment. However, so long as we have coded our widgetized area correctly and added widgets to it, we should see a useful addition here.

Adding Support for Visual Modifications

The other types of functions most commonly added to functions.php involve giving your users the ability to make visual changes to the theme from directly within the admin Dashboard.

Adding Support for Custom Headers

It’s typical that users with a particular theme on their website will want to change the header to one of their own creations, and WordPress gives us a really easy, standardized method of doing so. In order to make this happen, WordPress provides us with a set of code additions that we’ll need to build our functions.php file:

chapter_06/functions-php-custom-header.php
<?php

// Four constants that must be defined in order for the custom image 
// header to work properly
define('HEADER_TEXTCOLOR', 'ffffff'),
define('HEADER_IMAGE', get_bloginfo('styesheet_directory') .↵
  '/images/default_header.jpg'), 
define('HEADER_IMAGE_WIDTH', 900); 
define('HEADER_IMAGE_HEIGHT', 150);

// Include the header within the theme
function header_style() {
    ?><style type="text/css">
        #header {
            background: url(<?php header_image(); ?>);
        }
    </style><?php
}

// Include the header within the admin interface
function admin_header_style() {
    ?><style type="text/css">
        #headimg {
            width: <?php echo HEADER_IMAGE_WIDTH; ?>px;
            height: <?php echo HEADER_IMAGE_HEIGHT; ?>px;
            background: no-repeat;
        }
    </style><?php
}

// Enabling the custom image header
add_custom_image_header('header_style', 'admin_header_style'),

You’ll notice that there are four basic blocks of code: the first defines four constants; the second adds the header to the front end of the theme; the third adds the header to the administrative portion of the theme; and the last actually enables it all within WordPress. From an editing perspective, it’s important to pay attention as a theme developer to the first code block where we define our constants. Make sure to input the header dimensions accurately, as well as describe the location of the header image, and the color of any text that is added to the header. Without these constants, the custom header will simply fail to work.

Following the constants definition, the remaining three code blocks comprise pretty much our standard WordPress magic. First, we’ll create a function that will load with the wp_head action hook that adds the header image and its attributes into your theme. The next code block loads the header to the admin Dashboard, followed by our activation function in add_custom_image_header(), which specifically calls the two functions we’ve just defined.

Adding Support for a Custom Background

In what may be the granddaddy of easy functionality to add to any theme, WordPress has a simple method that gives your users the ability to add a custom background to their themes. In your functions.php file, add the following line of code:

<?php add_custom_background(); ?>

Doing this will automatically add a set of functionality to your theme that will allow the website administrator to see the existing background image of the theme, upload a background to replace the old one, and tweak several of the commonly modified attributes of the background. Take a look at Figure 6.4.

Adding a custom background themes custom backgrounds backgrounds, custom functions.php file custom backgrounds

Figure 6.4. Adding a custom background

If you were expecting a more complicated process, don’t knock it. Every once in a while you’re given a gift, and this is one of them!

Does My Functionality Belong in a Plugin or Theme?

While you can technically add functionality wherever you like in your theme, the question of where it’s appropriate to do so can be a bit murky when considering both the flexibility of WordPress and the divergent intentions of different web developers. Before we examine these nuances, though, let’s first define exactly what we mean by functionality.

Defining Functionality

The term functionality is a common buzzword that is thrown around fairly loosely these days by developers, designers, and clients alike, but exactly what are we talking about when we reference it? For the most part, just about anybody involved would agree that it’s a general term describing a specific feature set that has been introduced into a system. Within WordPress, almost all types of functionality can be broken down into four primary categories:

  • core WordPress functionality

  • functionality that enhances existing feature sets within core WordPress

  • functionality that introduces entirely new feature sets unavailable within core WordPress (including third-party application integration; for example, Twitter)

  • functionality that aids a specific theme in handling variables from a design and layout perspective

Whether you’re looking to add a real-time feed of Tweets to your sidebar or a jQuery image gallery on your home page, or just to set up your site to be ranked better in search engines, the categories listed should cover just about anything you want to throw at WordPress. If we assert that all functionality in WordPress falls within one of these four categories, and consider that WordPress provides a logical location to house operations, we can project whether a specific piece of functionality belongs within a plugin or within a theme.

Core WordPress functionality is included within WordPress, and should never be directly edited at any time (if you do, bad stuff can happen; think “removing random pieces of your engine just to see what happens”). Functionality that either enhances existing WordPress core features or introduces brand new features typically belongs as plugins, so that they can be added and removed as necessary. Likewise, functionality that aids a theme belongs within that theme, but it’s useful to note that it’s scripting that helps display specific pieces of content rather than add or extend functions. In this way, the intent of the scripting is different; it’s more about display logic than it is about site functionality, and it’s probably the most important distinction to make in determining where to place your site’s custom functionality.

The Difference between Display Logic and Site Functionality

Almost all functionality in WordPress is written in one of two languages: PHP or JavaScript. After all, whether you’re creating a custom jQuery script to add a behavior to a slide show or modifying The Loop to add the three most recent posts in the Featured category to the front page, you are really working on the site’s functionality. Right?

Sort of.

The truth is that while you are, indeed, working with functional pieces of scripting on your site, you should be able to squarely place any scripting into one of two categories. The script either adds to or enhances the actual features of your WordPress site (site functionality), or assists you in displaying that information to your audience (display logic). We all have a reasonable idea of what site functionality is, but display logic has everything to do with how we actually display useful data within the context of the theme. Common examples of display logic include:

  • registering sidebars and widgetized areas

  • registering new WordPress menus

  • inserting custom conditional logic into The Loop

  • using post thumbnail scripting references such as TimThumb

Incorporating prefabricated site functionality via the plugin system by customizing a theme’s display logic is the most common form of WordPress development performed by the typical WordPress developer, as most of us spend our time finding slicker and more effective ways of integrating existing tools across the Web to create client solutions. Often, the difference between good and poor coding practices is in recognizing the difference between actual site functionality and display logic, and coding each in the appropriate location.

A Case Study: ABC Real Estate

So if this is all as clear as mud, let’s take a look at a practical example. Suppose that we have a new client—ABC Real Estate—who’d like us to develop a new website built upon WordPress with the following functionality requests:

  • some form of event management system, as it will be running regular seminars

  • that each property be displayed in a constant, intuitive way with space for multiple photos (to vary per house listing)

  • six featured properties in a specific format to be selected for the home page

  • site integration of Facebook comments so that visitors can easily share potential homes with their friends

Each of these requests seems more than reasonable and intuitive for a real estate website, but let’s sort out exactly where we’d add each piece of functionality listed.

Some Form of Event Management System

This one is relatively simple. Because WordPress lacks an event management system in its core, we’ll need to add one via the plugin system. Could we write our own and add it directly to the theme itself? Technically, we could, but it would make little sense, as there are already so many event management systems available to try in a heartbeat. Furthermore, if we were absolutely bent on writing our own system, it would be easiest to contain all the files necessary in their own place to keep it tidy. Sounds like a plugin.

Each Property Displayed in a Constant, Intuitive Way

This one is a touch more complex, and a bit of a trick question. Since we’re talking about how elements are displayed, you might think we’re immediately in the realm of display logic. However, WordPress 3.0 introduced the notion of post types, which allows for developers to create a certain display format for a specific type of post. You can collect a discrete set of data within the WordPress admin for each record within the post type, and then output that record to a post template inside the theme, allowing the post to be output to the screen in a unique way. Because of the particular way that post types operate, you are essentially forced to create both display logic as well as site functionality when you work with them. We’ll go over this in a bit more detail further on in this chapter.

Six Featured Properties in a Specific Format for the Home Page

This is display logic. We’re adding nothing new here at all, but rather picking specific pieces of stored content from the database. This is always done directly within the theme.

Site Integration of Facebook Comments

Third-party application integration—in this case, Facebook. Piece of cake; we’ll add one of the myriad Facebook commenting plugins available for WordPress and integrate it appropriately.

My Way of Adding Site Functionality Works for Me!

And to that we say: we completely understand where you’re coming from, but allow us to make a few compelling points that just might change your mind.

First of all, if you are developing site functionality yourself, you’re likely to find it more useful to do so within the context of a plugin for purposes of portability, rather than directly within the theme. After all, even after a job has been completed and the site launched, a large percentage of developers retain the intellectual property rights of programs that they develop and utilize within sites they work on; sooner or later there is a need to reuse the same code (or a version of it) for another project. Plugins make this site functionality portable and easy to install, saving quite a bit of time in the long run.

Because WordPress plugins are structured to maintain all their files in separate directories away from other plugins and core WordPress features, they inherently provide order to the functions written throughout the site. For instance, if you are having an issue with the meta description on the home page and you know you are using an SEO plugin that handles that function (easily looked up by referencing the active plugin listing in the WordPress admin), you’ll know exactly where to begin investigating the source of the issue, even if you weren’t the original developer. In this way, plugins can actually provide a loose form of documentation in and of themselves, giving developers reasonable clues as to where certain functions might live, even in the poorest-documented of sites.

Troubleshooting is another fabulous reason to maintain site functionality within plugins rather than embed it directly into the theme. Adding new features to a WordPress site can occasionally cause conflicts and break a website, causing any number of display or performance issues that need to be corrected. When such issues go bump in the night, most seasoned developers begin examining existing plugins to see where scripting plugins may be happening. Using WordPress’s plugin system to activate and deactivate plugins provides a handy way to eliminate active scripts running on the site, and then bring them back one by one to determine which are the offending scripts. Without the ability to turn plugins on and off, a developer can be stuck trying to sort out exactly which scripts are conflicting with one another and causing a buggy result to the end user.

Finally, don’t underestimate the importance of flexibility in your website functionality. The more of the site’s core functionality that is directly built into the theme, the more difficult it becomes to make design changes to that theme, or even swap it out entirely. It may sound clichéd, but the Web is constantly shifting, and, ultimately, so will your site’s needs. Hard-coding site functionality into a theme can lead to time-consuming edits, changes, and overhauls in the long term (and often the short term) as you realize that what you thought was crucial yesterday—basing your entire site development on it—is entirely obsolete next week. Honestly, it has happened to the best of us.

Breaking the Rules

“All right,” we hear you say. “That’s fine, but I have a good reason to deviate …” Every subjective argument like this has solid reasoning to go your own way, and it’s useful to point out a few here.

Reason #1: Post Types

In our case study, we discussed putting together a customized post type to handle the display format for a property listing. Pragmatically, this involves putting two pieces of code together: an array initializing the data for the post type, and the post template to handle the display within the context of the theme. While the second component here is clearly an issue of display logic, the array initializations are a bit more fuzzy. This function is commonly defined within the theme’s functions.php file, but it’s important to note that it could be defined with a functions file initialized within the plugin system. In many ways, this makes a touch more sense as it keeps a clean separation between site functionality and design components, and would ensure that the site’s functionality was retained if you were to swap themes out down the track. As of this writing, initializing the array within the theme’s functions.php file is clearly the most common practice, but it’s certainly a gray area.

Reason #2: Specialized Page Templates

Occasionally, it becomes important to create a page on a WordPress site that performs a particular function. Perhaps you’re framing an item from another site, or pulling in some type of custom functionality that isn’t really conducive to working within the constructs of the standard WordPress page template and content editor. When this is the case, a usual practice is to register a new page template with the standard WordPress syntax in the template file, and then include the functionality directly within that page. In this instance, the functionality is not portable to other sites at all, but often it is done in a situation where that is unnecessary.

Reason #3: Protecting the Client from Themselves

As much as we’d all like to believe that WordPress is a bulletproof system that clients are unable to break, we know that’s inaccurate. Occasionally there is a good reason to hardcode. For example, let’s say you have a client who has to edit the sidebar on their website, but continually adds to or edits the wrong item. In this instance, it can be useful to hardcode simple elements into the sidebar that you’re reasonably sure the clients themselves will never need to update, guarding against the possibility of accidentally deleting it. Examples of what might be hardcoded include an email opt-in box or social media connection buttons.

Reason #4: Specialized Products for a Specific Industry

There are many theme developers out there who build targeted WordPress themes tailored to certain industries. These themes lack a certain amount of flexibility, but the upshot is that for the target market they serve, the additional flexibility is unnecessary. Examples of this include real estate-specific themes, product review themes, or question-and-answer aggregation themes.

Reason #5: Time and Budget Considerations

Point blank, it’s sometimes faster to code directly into a theme than to make it modular and use a plugin. When time is a factor or your client has a tight budget, a legitimate reason exists to cut corners and code site functionality directly into the theme. It’s important to note that this is certainly not a best practice, but it’s a reason to do what you need to do to get the job done.

Looking Good

Ultimately, themes are all about making your site look pretty, and it’s easy to do if you keep in mind a few points:

  • Themes revolve around moving template tags into different positions within your page templates. For the most part, every template will have a header and a footer, inserting page logic in the middle via our trusted friend and ally, The Loop.

  • There are some linear rules for determining how to name your template files, so that they automatically style the types of content you want them to.

  • You can use page templates to allow users greater control in the page editing screen over how certain pages appear.

We also learned how to add functionality such as widgetized areas in a theme’s functions.php file, and discussed the difference between site functionality and display logic. We’ve made the case that the best practice for adding functionality is to code display logic directly into the theme, while creating site functionality within the plugin system.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset