Creating Your Own WordPress Theme

Professional WordPress Design and Development bookCreating Your Own WordPress Theme

Now you know how to install and activate a theme on your site as well as what the different aspects of the theme are. It’s time to take the next step and make your own theme. You can start a theme from scratch, but why not stand on the shoulders of giants and start with a theme that is similar to the look you want? Or, if you cannot find one, start with a theme framework where most of the heavy lifting is done for you. There is no sense in reinventing the wheel, especially when you can use the power of open source software and start from working code.

Starting from a Working Theme

Sometimes it is easiest to find a theme close to what you have in mind and modify it. At the minimum, you can add your own logo. Of course you have to pay special attention to the licensing on the theme. Conveniently, themes in the wordpress.org Theme Directory are all GPL themes, so you can modify and use them however you desire.

Things to consider when starting from a working theme include:

  • Licensing on the original theme

  • Code quality

  • How much modification will be required

  • Source artwork for the creative assets

You will want to make sure that you are permitted to change the source theme you are starting with. You will also want to review the code quality of the theme, because you will be the one making the modifications going forward. Does the theme accomplish the same presentation goals as your site, template-wise; does it convey your data the way you want it conveyed? There is no point in starting with a theme that you have to completely retool. Does the theme have enough CSS hooks for you to style? Was search engine optimization (SEO) a consideration when the theme was developed? How much modification will be needed to meet your requirements and will you be happy with the end result? Finally, does the theme come with source art, like the original Photoshop document, for you to modify? If not, do you need it, or will you be able to re-create any assets you must have?

You have many considerations when developing a new or modified theme for either yourself or a client. The convenience of modifying a pre-built theme is quite a temptation to get a site up and running and out the door quickly. In practice, many sites have been built this way, where a client could select a stock template with a few minor modifications needed to quickly launch a new site. The catch is when a site goes beyond these simple modifications and you are stuck with modifying a poorly built theme. For that reason, even if a client likes a particular theme preview, you may find it easier in the long run to rebuild a similar theme from scratch with the Sandbox theme as a starting point.

Starting with the Sandbox Theme

Building a theme using a theme framework provides many advantages, especially for development teams. Because all of our deployed themes use this framework, we already have an idea of how the parts of the theme work. In addition, we have a common CSS vocabulary—rather than reading each theme’s style sheet, we can expect certain styles to be available because at the core is a theme framework. Finally, using a theme framework takes most of the heavy lifting out of the theme development process because many common problems and browser incompatibilities have already been addressed.

For example, the Sandbox theme framework has pre-built examples for several different web site styles. One-column, two-column (with the sidebar on the left or right), and three-column examples are shipped with the framework. All of these variants have been tried and tested in the current browsers and are known to work. This is extremely convenient when you need to start a site quickly. It should be noted that once you resize the sidebar widths in the CSS, you will have to tweak the entire CSS layout to accommodate different browsers’ rendering quirks (Internet Explorer will always cause you problems) but with a little arithmetic, it’s not too difficult to work out.

The Sandbox framework is very well thought out and loaded with CSS hooks for the body HTML element, each post, and each comment. For example, with a default Sandbox template, the body tag of each HTML document is multi-classed with a wide range of details. Using the Firebug add-on for Firefox, available online at http://getfirebug.com/, consider this inspection of a single-post page shown in Figure 8-1.

Inspecting WordPress page with Firebug

Figure 8-1: Firebug inspection of stock Sandbox theme CSS classes

NOTE: If you are not using Firebug for development of the front end of your web site, you are really missing out.  Firebug has proven to be the most valuable web developer’s tool in recent memory.

The body tag is classed with year, month, day, and hour of the post, as well as the category, tags, and author. If the post were tagged with multiple keywords or in multiple categories, they would each be listed. Similar functionality has recently been added to the WordPress core and will work just as well, and in fact, many framework-type themes are emulating this behavior because it is so powerful to the front end developer. We feel this stands as a further testament on why Sandbox is a great theme to begin your theme build.

This same multi-classed CSS also applies to the posts on a loop page and the comments. The vast array of CSS hooks allows for easy CSS styling and opens up a ton of possibilities. Posts could be styled by the time of day they were posted or change colors every month to give your site an “edition” feel.

Additionally, Sandbox is chock-full of microformat support. Microformats are part of the semantic web, where markup enhances the content by following certain conventions. Search engines and some browsers respect these conventions and augment the user experience with the additional structured content. You will see microformats in the author information and a few other spots throughout the Sandbox theme.

NOTE: In the Sandbox theme, each post is classed with the CSS class hentry. Hentry is part of the Atom microformat specification.

You will find that with the stock Sandbox installation your theme is very minimal and plain. That is entirely by design. Sandbox is intended to be a minimal theme, but is entirely functional. Some people find this type of theme very appealing; after all, beauty is in the eye of the beholder. For development, this is advantageous because you are not bringing any cobwebs with you. With Sandbox you are building up entirely from a solid CSS foundation.

Sandbox is widget compatible with dynamic sidebars. It does, however, have only the two traditional sidebars built in, whereas some newer theme frameworks have multiple widget-ready zones—sidebars seems a misnomer when they are placed in different locations on the page.

The Sandbox theme does have its flaws. The minimal CSS is both a blessing and a burden. The default appearance looks basic and unfinished. No matter what, you will have to add some styling, which is expected. But with some theme frameworks, the default styles are at least presentable.

The Sandbox theme also does not include CSS reset style sheet. This leaves browsers to render unstyled elements in their own different styles, which can lead to box model rendering problems. The simple fix is to use a reset style sheet at the beginning of the theme style sheet or refer to other reset style sheets such as Eric Meyers’ which is available online at http://meyerweb.com/eric/tools/css/reset/.

If you are developing several themes for various clients, like we are, we recommend keeping a modified Sandbox theme in your toolbox. Our modified Sandbox theme is the starting point for all internally developed themes. This “Better Sandbox” theme addresses the preceding issues, including delineating some base typography to build on and resetting elements to improve browser rendering. Our foundation theme also includes many common styles that are used across sites but are lacking in the stock Sandbox. These additional styles include classes like success and error for appropriate messages and extend the development team’s common vocabulary.

Several newer theme frameworks have built on the Sandbox ideas. These are discussed later in this chapter. You should try these other frameworks and make a decision for yourself. In our opinion, Sandbox continues to be an excellent theme foundation to start with and it is what we continue to use daily. The balance between learning a theme framework on top of the WordPress framework and being able to dive right in on the PHP fits our needs nicely.

Creating Your Own Theme: Getting Started

Creating your own theme can be as simple or as complicated as you want it to be. Sometimes, you merely want to change a logo or a color and it is a basic process. Often, you are creating a theme from scratch to meet a certain need or condition, or solely to obtain a specific design look and feel. Whatever your motivations are, this section discusses the basics for getting a new theme and site design up quickly using the Sandbox theme as a foundation.

Essential File: Style.css

The style.css file is what WordPress uses to reference your theme, and this file is required for your theme to work. In practice, you could create a new theme with only a style sheet and index.php template file, though the index file can be empty. Using the power of WordPress’s theme hierarchy, WordPress automatically substitutes missing templates if your new theme does not have them. More on that later, but understand that is what allows you to get started creating your own theme.

NOTE: In practice, a style.css file is all you need to create a new theme. See the section on child themes later in the chapter.

When creating your own styles.css for your new theme, the first few lines are absolutely critical. These lines provide information to WordPress to use in the theme Control Panel and further reference your theme in the core. Your first few lines should read as follows (substitute your information, of course): 

/*

THEME NAME: MyTheme

THEME URI: http://www.mirmillo.com/mytheme/

DESCRIPTION: Theme for my new site.  Based on Sandbox.

VERSION: 1.0

AUTHOR: David Damstra (and friends)

AUTHOR URI: http://mirmillo.com/author/ddamstra

TAGS: sandbox, microformats, hcard, hatom, xoxo, widgets, blank slate,

starter theme, minimalist, developer

*/

The information here is pretty self-explanatory. There is an additional optional field for theme hierarchy, covered later in the chapter. Make sure your theme name is unique to your installation. If you intend to release your theme for public use, either for free or for a premium, you should try to come up with a unique name to reduce naming collision in the directory and other installations. In addition, if you are deriving your theme from another theme, license permitting of course, you should uphold the license and copyright information from the original theme. Once you have addressed this required information for WordPress, the remainder of the file is traditional CSS and subject to the rules and structure imposed as such.

Not all development shops use the child theme functionality that is covered later. In some cases, the workflow fits better if a new theme is created by copying and renaming the foundation theme to a new folder and revising the style.css to reflect the new project. This technique has pros and cons, but it works well for some teams because the foundation theme does not change often enough to warrant more complex methodologies. Plus, when you have a theme in production, you do not want a change to the parent theme to cause a cascading rendering issue in your successfully deployed site. Creating a copy and making a working theme in this new directory removes the dependency on future browser rendering testing, which is a time- and human-intensive procedure—that is, no one has automated this procedure yet. In the event that there is a substantial change to the parent theme, changes can be ported to the derivative themes on a case-by-case basis and tesed as needed. Making a copy of the foundation theme also presents the advantage of creating a hand-crafted CSS file by modifying the actual theme files rather than overriding the styles and carrying that additional byte baggage.

The next step in your CSS file is to determine the layout of your web site. Sandbox provides several example layouts for the common web site arrangements, so generally the next line in the CSS is usually pulling in this structure, like so:

/* Two-column with sidebar on left from the /examples/ folder  */

@import url(‘examples/2c-l.css’);

This line of code imports the two-column with the sidebar on the left-hand side example layout from the Sandbox examples. Because we are starting with a full copy of the stock Sandbox theme, we have access to the pre-built examples. Notice the relative path reference to the 2c-l.css file. The example layouts are excellent ways to get your site layout established and then modify them to match your specific design as needed. Of course, you do not have to start with the example layouts and could build your own structure from scratch. If you intend to use one of the CSS grid layouts that are currently in fashion, this may be the way to go. You can mix and match different CSS frameworks to fit your needs.

For example, as previously mentioned the Sandbox theme is a very minimal theme and does not address typography or some common use classes. In some themes we have tried various stock typography CSS frameworks to get up and going quickly. For example:

/* blue trip typography */

@import url(‘bluetrip/screen.css’);

In this example theme we imported the nice Blue Trip Typography CSS from bluetrip.org. We stripped out all the styles except the typography classes to reduce conflicts. The downside to importing these style sheets and using pre-built classes is that your sheets may contain extraneous rules that you will never use, or do not know they exist, and that extra baggage is carried down to the browser in added load time. There certainly is a trade-off in using some pre-fabricated CSS versus handcrafting it all yourself for your specific needs. This is a choice you have to make as a developer.

Moving forward, CSS rules are written out in the style.css file to turn your minimal layout into the professionally designed theme you are creating. CSS coding is outside the scope of this book and if done well, is an art and skill. Again, Wrox has several great books on working with CSS.

Showing Your Content: Index.php

When creating your theme, you often have a chicken-and-egg problem. Maybe you are lucky and you know exactly what content is going to be published on your WordPress site, and exactly how it’s going to be structured. Maybe you even know exactly how the final theme is going to look, or you’ve had a professional designer create some mockups for you. But odds are, your site is going to grow organically and to see how the design, and therefore the style sheet, is going to play out, you need to have some content to display.

You can use certain stock content files to import into your site and work through all the styles or you can start building your site.

index.php is the default template of your site. WordPress has a built-in decision engine that decides which type of information your visitor is requesting and then determines if there is a template file available for that information type. This hierarchy is covered later in the chapter, but the index.php template is the default, or template of last resort. If WordPress does not determine that there is a more specific template to use, index.php is it.

Usually the index.php file contains your standard loop. This is a traditional blog format where the posts are displayed in reverse chronological order. For example, this is the loop from the Sandbox:

<?php while ( have_posts() ) : the_post() ?>

    <div id="post-<?php the_ID() ?>" class="<?php sandbox_post_class() ?>">

        <h2 class="entry-title">

            <a href="<?php the_permalink() ?>"

                   title="<?php printf( __(‘Permalink to %s’,’sandbox’),

             the_title_attribute(‘echo=0’) ) ?>" rel="bookmark">

                <?php the_title() ?>

            </a>

        </h2>

        <div class="entry-date">

             <abbr class="published" title="<?php the_time(‘Y-m-dTH:i:sO’) ?>">

                <?php unset($previousday); printf( __( ‘%1$s – %2$s’, ‘sandbox’ ),

                the_date( ”, ”, ”, false ), get_the_time() ) ?>

            </abbr>

        </div>

        <div class="entry-content">

            <?php the_content( __( ‘Read More <span class="meta-nav">&raquo;</span>’,

             ‘sandbox’ ) ) ?>

            <?php wp_link_pages(‘before=<div class="page-link">’

               . __( ‘Pages:’, ‘sandbox’ ) . ‘&after=</div>’) ?>

        </div>

        <div class="entry-meta">

            <span class="author vcard">

                <?php printf( __( ‘By %s’, ‘sandbox’ ), ‘<a class="url fn n" href="’ .

                 get_author_link( false, $authordata->ID, $authordata->user_nicename ) .

                 ‘" title="’ . sprintf( __( ‘View all posts by %s’, ‘sandbox’ ),

                 $authordata->display_name ) . ‘">’ . get_the_author() . ‘</a>’ ) ?>

            </span>

            <span class="meta-sep">|</span>

            <span class="cat-links">

                <?php printf( __( ‘Posted in %s’, ‘sandbox’ ),

                  get_the_category_list(‘, ‘) ) ?>

            </span>        

            <span class="meta-sep">|</span>

            <?php the_tags( __( ‘<span class="tag-links">Tagged ‘, ‘sandbox’ ), ", ",

             "</span>nttttt<span class="meta-sep">|</span>n" ) ?>

            <?php edit_post_link( __( ‘Edit’, ‘sandbox’ ),

                  "ttttt<span class="edit-link">",

             "</span>nttttt<span class="meta-sep">|</span>n" ) ?>              

            <span class="comments-link">

                <?php comments_popup_link( __( ‘Comments (0)’, ‘sandbox’ ), __(

                ‘Comments (1)’, ‘sandbox’ ), __( ‘Comments (%)’, ‘sandbox’ ) ) ?>

            </span>  

        </div>

    </div><!– .post –>

    <?php comments_template() ?>

<?php endwhile; ?>

As covered in Chapter 5, the loop is really the heart of WordPress. It is the most important concept to grasp because it is how your content is read out to be published. The Sandbox main loop is a traditional loop but includes all the semantic HTML, microformats, and CSS hooks that make the Sandbox theme a great foundation.

There certainly is a ton of stuff going on in that code snippet, but if you break it apart into the discrete sections and cross reference it with the rendered HTML, it will all come together quite quickly. Realize, also, that this loop uses many Sandbox-specific functions to simplify the coding, even if it appears to complicate the template. Theme functions are covered later in this chapter.

Showing Your Content in Different Ways: Index.php

The index.php file is really the most important template file in your theme. Although you cannot have an active theme in WordPress without styles.css—because that is how WordPress knows you have the theme available—index.php does the heavy lifting.

In the early days of WordPress, the index template was the only template. The whole theme was just this one file, and it was really just the loop. That worked fine for WordPress when you used it as a traditional blog and this bloggy look is probably why WordPress is still derided as a blog engine.

We hope you are reading this book because you know WordPress can be so much more, or if you did not know, you are realizing it now. Your index template is very important; we cannot stress that enough. It is the template of last resort that WordPress will use when it cannot find a more specific one to use (see “Template Hierarchy,” later in the chapter.)

Nevertheless, your index file does not have to be a single loop showing your most recent posts. That is very traditional, and may work well for your site, but you can branch out. Your index file can be structured in so many different ways, it is truly limitless. It could contain multiple different loops from different tags or categories, or it could contain no loops at all. The index template could function as your error page, where you have more specific templates for every other piece of content in your site. 

This article is excerpted from chapter 8 "Theme Development" of the book "Professional WordPress Design and Development" by Hal Stern, David Damstra, Brad Williams (ISBN: 978-0-470-56054-9, Wrox, 2010, Copyright Wiley Publishing Inc.)

Tags:

Comments

One response to “Creating Your Own WordPress Theme”

  1. Anonymous says:

    is that true?
    care to explain?
    just wondering
    ;-D

Leave a Reply

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