Chapter 6: Digging into Advanced Theme Development

In This Chapter

arrow.png Customizing themes

arrow.png Creating new templates

arrow.png Activating custom menus

arrow.png Exploring custom post types

arrow.png Understanding post formats

arrow.png Using post thumbnails for feature images

arrow.png Building a theme options page

The previous chapters of this minibook describe WordPress themes and using their structure to build your site. Delving into deeper topics can help you create flexible themes that offer users options to control the theme.

Whether you’re building a theme for a client, the WordPress.org theme directory, or yourself, adding advanced theme features can make theme development easier and faster with a high-quality result. With these advanced theme concepts and tools, you can build robust, dynamic themes that allow for easier design customization and offer a variety of layout options.

Beyond just tools and methods of advanced theme development, this chapter provides some development practices that help projects succeed.

Getting Started with Advanced Theming

Before themes were added to WordPress, customizing the design of the site meant modifying the main WordPress index.php file and the default print.css file. Version 1.5 added the first theme support and rudimentary child theme support. Over time, WordPress began to support other features, such as custom headers, custom backgrounds, and featured images.

Additionally, the capabilities of themes have grown steadily. Incremental improvement — beginning with a small, simple starting point and improving it over time — works very well in theme development. By developing incrementally, you can build a theme from start to completion from an existing, well-tested theme (most themes are part of a larger incremental improvement process) and maximize your development time. I can’t think of a single theme I’ve developed that wasn’t built on another theme.

tip.eps There isn’t a need to develop each theme from scratch. Choosing a good starting point makes a big difference to how quickly you can get your project off the ground.

Finding a good starting point

Choosing a solid starting point to build your latest and greatest theme design on can be time consuming. Although exploring all the available themes in detail is tempting, I find exhaustive searches waste more time than they save.

Begin with the most current theme unless there’s a more suitable one. Because the design and capabilities of the theme were recently implemented, modifying it to meet your current project’s needs is faster than rediscovering all the nuances of an older, unfamiliar theme.

You might wonder whether I ever build themes off other designers’ themes. I have. These days, if a new theme comes out that shows how to integrate some new feature, I play around with the theme to understand the concept but always go back to one of my themes to implement the modification. The reason for this is simple: If I can implement the feature into my own design, I have a much better appreciation for how it works. Allowing someone else’s code or design to do the heavy lifting can place a limitation on how I use that feature.

tip.eps If you’re new to theme development and haven’t produced a theme of your own, start with the WordPress default theme, Twenty Twelve. (See Chapter 1 in this minibook for a full analysis of the Twenty Twelve theme.) This theme is developed for helping new theme developers discover how themes work.

All the examples in this chapter are built off the WordPress default Twenty Twelve theme, unless noted otherwise.

Customizing the theme to your needs

After you select a theme for your project, you should create a copy of the theme. This way you can look at the unmodified version in case you accidentally remove something that causes the theme or design to break.

When you find code and styling that you don’t need anymore, comment it out rather than delete it. This removes the functionality but still allows you to add it back later if you change your mind.

A line of PHP code can be commented out by adding // in front of it. For example:

// add_editor_style();

CSS can be commented out by wrapping a section in /* and */. For example:

/*#content {

margin: 0 280px 0 20px;

}

*/

#primary,

#secondary {

float: right;

/* overflow: hidden;

*/

width: 220px;

}

HTML code gets commented out using brackets starting with <!-- and ending with --> surrounding the code. For example:

<!--<div id="content">this is a content area</div>-->

tip.eps When you start finalizing the theme, go through the files and remove any blocks of commented styling and code to clean up your files.

Adding New Template Files

Chapter 3 of this minibook introduces the concept of template files and gives you an overview of the template files available to you. Chapter 5 of this minibook explains the idea of overriding template files with child themes. The following sections explore some advanced uses of template files.

Although you rarely need to use all these techniques, being fluent in your options gives you flexibility to address specific needs quickly when they come up.

Creating named templates

WordPress recognizes three special areas of a theme: header, footer, and sidebar. The get_header, get_footer, and get_sidebar functions default to loading header.php, footer.php, and sidebar.php, respectively. Each of these functions also supports a name argument to allow you to load an alternative version of the file. For example, running get_header('main') causes WordPress to load header-main.php.

You might wonder why you would use a name argument when you could just create a template file named whatever you like and load it directly. The reasons for using the get_header, get_footer, or get_sidebar functions with a name argument are

check Holding to a standard naming convention that other WordPress developers can easily understand

check Automatically providing support for child themes to override the parent theme’s template file

check Offering a fallback that loads the unnamed template file if the named one doesn’t exist

remember.eps In short, use the name argument feature if you have multiple, specialized header, footer, or sidebar template files.

You can use this named template feature along with the Theme Options discussed in the “Exploring Theme Options” section, later in this chapter, to allow users to easily switch between different header, footer, and sidebar styles. On the Theme Options page, you can give the user the ability to choose the specific header, footer, or sidebar template file he or she wants, giving users an easy way to change the layout or design of the site. A good example of content you could add to a different sidebar file can be found in the nearby “WP_Query for category content” sidebar, which discusses displaying a list of recent posts and filing them in a specific category in the sidebar of your site.



Creating and using template parts

A template part is very similar to the header, footer, and sidebar templates except that you aren’t limited to just header, footer, and sidebar.

The get_header, get_footer, and get_sidebar functions allow for code that's duplicated in many of the template files to be placed in a single file and loaded by using a standard process. The purpose of template parts is to offer a standardized function that can be used to load sections of code specific to an individual theme. Sections of code that add a specialized section of header widgets or display a block of ads can be placed in individual files and easily loaded as a template part.

You load template parts by using the get_template_part function. The get_template_part function accepts two arguments: slug and name. The slug argument is required and describes the generic type of template part to be loaded, such as loop. The name argument is optional and selects a specialized template part, such as post.

A call to get_template_part with just the slug argument tries to load a template file with a filename of slug.php. Thus, a call to get_template_part('loop') tries to load loop.php, and a call to get_template_part('header-widgets') tries to load header-widgets.php. See a pattern here? Slug refers to the name of the template file, minus the .php extension, because WordPress already assumes that it's a PHP file.

A call to get_template_part with both the slug and name arguments will try to load a template file with a filename of slug-name.php. If a template file with a filename of slug-name.php doesn't exist, then WordPress will try to load a template file with a filename of slug.php. Thus, a call to get_template_part('loop', 'post') first tries to load loop-post.php followed by loop.php if loop-post.php doesn't exist; a call to get_template_part('header-widgets', 'post') first tries to load header-widgets-post.php followed by header-widgets.php if header-widgets-post.php doesn't exist.

The Twenty Twelve theme offers a good example of the template part feature in use. It uses a template part called content to allow the page or post content, within The Loop, to be get into individual files.

remember.eps The Loop is the section of code found in most theme template files that uses a PHP while loop to loop through the set of post, page, and archive content (to name a few) and display it. The presence of The Loop in a template file is crucial for a theme to function properly. Chapter 3 in this minibook examines The Loop in detail.

Twenty Twelve's index.php template file shows a template part for the content template part in action:

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

<?php get_template_part( 'content', get_post_format() ); ?>

<?php endwhile; ?>

Loading the content by using a template part, Twenty Twelve cleans up the index.php code considerably when compared with other themes. This cleanup of the template file code is just the icing on the cake. The true benefits are the improvements to theme development.

Twenty Twelve's index.php template file calls for a template part with a slug of content and a name of get_post_format(). The get_post_format(); tag pulls in the defined format for the post (check out the section later in this chapter titled "Adding support for post formats"), such as asides, image, link, and so on. If a post format exists, the get_template_part(); calls it in. For example, if the post format is defined as aside, the get_template_part(); pulls in the content-aside.php template. If no post format has been defined, Twenty Twelve simply uses the content.php template. A child theme (child themes are discussed at length in Chapter 5 of this minibook) could supply a content.php file to customize just The Loop for index.php. A child theme can do this without having to supply a customized index.php file because of Twenty Twelve's use of template parts and using both arguments of the get_template_part function.

With Twenty Twelve's code for the header, Loop, sidebar, and footer placed into separate files, the template files become much easier to customize for specific uses. You can see the difference by comparing the page.php to the full-width.php template files:

The page.php listing:

<?php get_header(); ?>

     <div id="primary" class="site-content">

     <div id="content" role="main">

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

            <?php get_template_part( 'content', 'page' ); ?>

            <?php comments_template( '', true ); ?>

       <?php endwhile; // end of the loop. ?>

    </div><!-- #content -->

    </div><!-- #primary -->

<?php get_sidebar(); ?>

<?php get_footer(); ?>

The full-width.php listing:

/* Template Name: Full-width Page Template, No Sidebar */

<?php get_header(); ?>

<div id="content" role="main">

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

          <?php get_template_part( 'content', 'page' ); ?>

          <?php comments_template( '', true ); ?>

     <?php endwhile; // end of the loop. ?>

</div><!-- #content -->

</div><!-- #primary -->

<?php get_footer(); ?>

Other than the full-width.php having the Template Name comment at the top, allowing it to be used as a page template (discussed in the upcoming "Using page templates" section), the only difference is that page.php has the get_sidebar function call and full-width.php does not. With just this modification and a few styling rules added to the CSS, the theme now has a page template that doesn't have a sidebar.

You might wonder how the preceding example shows the value of template parts if it is really about the get_sidebar function. Although the get_sidebar function is the feature of the previous example, the unsung hero is the get_template_part function.

Before template parts, the full Loop code would be duplicated in the page.php and full-width.php files. This means that a modification to the page.php file's Loop code would also require the same modification to the full-width.php file. Imagine if you had to make the same modification to five template files. Repeatedly making the same modifications quickly becomes tiring, and each modification increases the chance of making mistakes. Using a template part means that the modification needs to be made only one time.

Looking at the page.php and full-width.php example, the get_template_part call allows for easily creating as many customized page templates as needed without having to duplicate The Loop code. Without the duplicate code, the code for The Loop can be easily modified in one place.

tip.eps When you start duplicating sections of code in numerous template files, place the code in a separate file and use the get_template_part function to load it where needed.

Exploring content-specific standard templates

The template files discussed so far span a wide scope of site views specific to the view and not the content. For example, the category.php template file applies to all category archive views but not to a specific category, and the page.php template file applies to all page views but not to a specific page. However, you can create template files for specific content and not just the view.

Four content-specific template types are available: author, category, page, and tag. Each one allows you to refer to specific content by the term’s ID (an individual author’s ID, for instance) or by the slug.

remember.eps The slug discussed in this section differs from the slug argument of the get_template_part function described in the preceding section. For this section, slug refers to a post, page, or category slug (to name a few), such as a Press Releases category having a slug of press-releases or a post titled "Hello World" having a slug of hello-world.

For example, imagine that you have an About Us page with an id of 138 and a slug of about-us. You can create a template for this specific page by creating a file named either page-138.php or page-about-us.php. In the same way, if you want to create a template specific to an awesome author named Lisa with an id of 7 and a slug of lisa, you can create a file named either author-7.php or author-lisa.php.

Creating a template by using the slug can be extremely helpful for making templates for sites that you don't manage. If you want to share a theme that you created, you could create a category-featured.php template, and this template would automatically apply to any category view that has a slug of featured.

Using categories as the example, the file naming convention is as follows:

check A template with the filename category.php is a catchall (default) for the display for all categories (alternatively, a template with the filename of archives.php will display categories if a category.php does not exist).

check Add a dash and the category ID number to the end of the filename (shown in Table 6-1) to specify a template for an individual category.

check Alternatively, you can add a dash and the category slug to the end of the filename (shown in Table 6-1) to define it as a template for that particular category. For example, if you have a category called Books, the category slug is books; the individual category template file would be named category-books.php.

check If you don't have a category.php, an archives.php, or category-#.php file, the category display pulls from the Main Index template (index.php).

Table 6-1 gives you some examples of file naming conventions for category templates.

Table 6-1 Category Template File Naming Conventions

If the Category ID or Slug Is . . .

The Category Template Filename Is . . .

1

category-1.php

2

category-2.php

3

category-3.php

books

category-books.php

Movies

category-movies.php

music

category-music.php

remember.eps Because creating a template by using slugs is so useful (and because an ID is relevant only to a specific site), you might wonder why the id option exists. The short answer is that the id option existed before the slug option; however, it is still valuable in specific instances. You can use the id option for a content-specific template without worrying about the customization breaking when the slug changes. This is especially helpful if you set up the site for someone and can't trust that he or she will leave the slugs alone (such as changing a category with a slug of news to press-releases).

Using page templates

Although the page-slug.php feature is very helpful, sometimes requiring the theme's user to use the name you choose for a specific feature is too difficult or unnecessary. Page templates allow you to create a standalone template (just like page.php or single.php) that the user can selectively use on any specific page he or she chooses. As opposed to the page-slug.php feature, a page template can be used on more than one page. The combined features of user selection and multiple uses make page templates a much more powerful theme tool than page-slug.php templates.

For more on page templates, see Chapters 1, 3, and 5 in this minibook.

To make a template a page template, simply add Template Name: Descriptive Name to a comment section at the top of the template file. For example, the following code is the beginning of the onecolumn-page.php page template file in the Twenty Twelve theme:

<?php

/**

* Template Name: Full-width Page Template, No Sidebar

*

* Description: Twenty Twelve loves the no-sidebar look as much as

* you do. Use this page template to remove the sidebar from any page.

*

* Tip: to remove the sidebar from all posts and pages simply remove

* any active widgets from the Main Sidebar area, and the sidebar will

* disappear everywhere.

*

* @package WordPress

* @subpackage Twenty_Twelve

* @since Twenty Twelve 1.0

*/

This registers the template file as a page template and adds Full-width Page Template, No Sidebar to the Page Attributes module’s Template drop-down list, as shown in Figure 6-1. (Check out Book IV, Chapters 1 and 2 for information on publishing pages.) Using a template on a static page is a two-step process: Upload the template and tell WordPress to use the template by tweaking the page’s code.

9781118383339-fg060601.tif

Figure 6-1: The Dashboard showing page attributes.

By providing a robust set of page templates, you can offer users of your theme an easy-to-use set of options for formatting their pages. These options can be used only for pages, but named header, footer, sidebar, and template parts can be used to offer users options on other site views.

Adding Theme Support for Built-In Features

The WordPress core offers a number of great tools that can easily be added to a theme to give the theme more customization options. WordPress provides you with several built-in features that give you the ability to enhance your site and theme. This section covers five of the most popular features, including

check Custom navigation menus

check Custom post types

check Custom taxonomies

check Post formats

check Featured images

Each of these features is part of the WordPress core; however, they aren’t activated by default. When you “add theme support,” you’re activating a built-in feature in your theme. Therefore, when you’re travelling around the WordPress community, whether it’s in a support forum or at a WordCamp event, and you hear someone say the theme supports a certain feature, you can smile because you know exactly what he’s talking about.

Activating support for these features in the theme you’re using involves a few steps:

check Core function: Add support for the feature in your theme by including the core function in your theme's Theme Functions template file (functions.php).

check Template function: Add the necessary function tags in your theme template(s) to display the features on your website.

check Templates: In some cases, you can create feature-specific templates to create enhancements to your site.

The following sections take you through each feature. You add the core function to your theme, add the function tags to your templates and, if indicated, create a feature-specific template in your theme that will handle the added features.

Adding support for custom menus

The WordPress menu-building feature is a great tool that WordPress offers to theme developers. Before the addition of this tool, theme developers implemented their own menu solution, creating a huge number of themes with navigation customization requiring coding and a small set of themes with very different ways of handling navigation. Creating complex, multi-level menus on your WordPress site takes just a few steps, as outlined in this section.

A navigation menu is a listing of links that displays on your site. These links can be links to pages, posts, or categories within your site, or they can be links to other sites. Either way, you can define navigation menus on your site with the built-in Custom Menus feature in WordPress.

It’s to your advantage to provide at least one navigation menu on your site so that readers can see everything your site has to offer. Providing visitors with a link — or several links — keeps with the point-and-click spirit of the web.

The Twenty Twelve theme already supports menus. Looking at Twenty Twelve's functions.php file, you can see that the following lines of code handle registering the theme's menu:

// This theme uses wp_nav_menu() in one location.

register_nav_menus( array(

'primary' => __( 'Primary Navigation', 'twentytwelve' ),

) );

This registers a single navigation area with a theme location name of primary and a human-readable name of Primary Navigation. With the Twenty Twelve theme active, click the Menus link on the Appearance menu to load the Menus page on the Dashboard and view the Primary Navigation menu location.

Core menu function and template tags

The Custom Menu feature is already built in to the default Twenty Twelve WordPress theme, so you don’t have to worry about preparing your theme for it. However, if you’re using a different theme, adding this functionality is easy:

1. Click the Editor link on the Appearance menu and then click the Theme Functions template file (functions.php).

The Theme Functions template opens in the text editor on the left side of the Edit Themes page.

2. Type the following function on a new line in the Theme Functions template file:

// ADD MENU SUPPORT

add_theme_support( 'nav-menus' );

3. Click the Update File button to save the changes to the template.

This template tag tells WordPress that your theme can use the Custom Menu feature, and a Menus link now displays on the Appearance menu on the Dashboard.

4. Open the Header template (header.php).

Click the Header link on the Edit Themes page to open the Header template in the text editor on the left side of the Edit Themes page.

5. Add the following template tag by typing it on a new line in the Header template (header.php):

<?php wp_nav_menu(); ?>

This template tag is needed so the menu you build by using the Custom Menu feature will display at the top of your website. Table 6-2 gives the details on the different parameters you can use with the wp_nav_menu(); template tag to further customize the display to suit your needs.

6. Click the Update File button at the bottom of the page to save the changes you made to the Header template.

9781118383339-tb060602.png

Figure 6-2 shows the default Twenty Twelve theme with a navigation menu (Home, About, and Blog) beneath the theme’s header graphic.

9781118383339-fg060602.eps

Figure 6-2: The Twenty Twelve theme with a navigation menu below the header.

A menu called Main was created on the WordPress Dashboard. (See Chapter 1 in this minibook to create menus in the WordPress Dashboard.) The template tag used in the theme to display the menu looks like this:

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

The HTML markup for the menu is generated as an unordered list, by default, and looks like this:

<ul id="menu-main" class="menu">

<li id="menu-item-53" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-53"><a href="/">Home</a></li>

<li id="menu-item-51" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-51"><a href="http://localhost/wpdemo/blog/">Blog</a></li>

<li id="menu-item-52" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-52"><a href="http://localhost/wpdemo/about/">About</a></li>

</ul>

Notice, in the HTML markup, the <ul id="menu-main" class="menu"> line defines the CSS ID and class.

The ID reflects the name that you give your menu. Because the menu is named Main, the CSS ID is menu-main. If the menu were named Foo, the ID would be menu-foo. By assigning menu names in the CSS and HTML markup, WordPress allows you to use CSS to create different styles and formats for your different menus.

When developing themes for either yourself or others to use, make sure that the CSS you define for the menus can do things like account for subpages by creating drop-down menus. You can accomplish this in several different ways; Listing 6-1 gives you just one example — a block of CSS that you can use to create a nice style for your menu. (This CSS example assumes that you have a menu named "Main"; therefore, the HTML and CSS markups use menu-main.)

Listing 6-1: Sample CSS for Drop-Down Menu Navigation

#menu-main {

....width: 960px;

....font-family: Georgia, Times New Roman, Trebuchet MS;

....font-size: 16px;

....color: #FFFFFF;

....margin: 0 auto 0;

....clear: both;

....overflow: hidden;

....}

 

#menu-main ul {

....width: 100%;

....float: left;

....list-style: none;

....margin: 0;

....padding: 0;

....}

 

#menu-main li {

....float: left;

....list-style: none;

....}

 

#menu-main li a {

....color: #FFFFFF;

....display: block;

....font-size: 16px;

....margin: 0;

....padding: 12px 15px 12px 15px;

....text-decoration: none;

....position: relative;

....}

 

#menu-main li a:hover, #menu-main li a:active, #menu-main .current_page_item a, #menu-main .current-cat a, #menu-main .current-menu-item {

....color: #CCCCCC;

....}

 

#menu-main li li a, #menu-main li li a:link, #menu-main li li a:visited {

....background: #555555;

....color: #FFFFFF;

....width: 138px;

....font-size: 12px;

....margin: 0;

....padding: 5px 10px 5px 10px;

....border-left: 1px solid #FFFFFF;

....border-right: 1px solid #FFFFFF;

....border-bottom: 1px solid #FFFFFF;

....position: relative;

....}

 

#menu-main li li a:hover, #menu-main li li a:active {

....background: #333333;

....color: #FFFFFF;

....}

 

#menu-main li ul {

....z-index: 9999;

....position: absolute;

....left: -999em;

....height: auto;

....width: 160px;

....}

 

#menu-main li ul a {

....width: 140px;

....}

 

#menu-main li ul ul {

....margin: -31px 0 0 159px;

....}

 

#menu-main li:hover ul ul, #menu-main li:hover ul ul ul {

....left: -999em;

....}

 

#menu-main li:hover ul, #menu-main li li:hover ul, #menu-main li li li:hover ul {

....left: auto;

....}

 

#menu-main li:hover {

....position: static;

....}

remember.eps The CSS you use to customize the display of your menus will differ; the example in the preceding section is just that, an example. After you get the hang of using CSS, you can try different methods, colors, and styling to create a custom look of your own. (You can find additional information about Basic HTML and CSS in Chapter 4 of this minibook.)

Displaying custom menus using widgets

You don't have to use the wp_nav_menu(); template tag to display the menus on your site, because WordPress also provides a Custom Menu widget that you can add to your theme, allowing you to use widgets, instead of template tags, to display the navigation menus on your site. This widget is especially helpful if you've created multiple menus for use in and around your site in various places. Have a look into Chapter 4 in this minibook for more information on using WordPress widgets.

Your first step is to register a special widget area for your theme to handle the Custom Menu widget display. To do this, open your theme's functions.php file and add the following lines of code:

// ADD MENU WIDGET

if ( function_exists('register_sidebar') )

    register_sidebar(array('name'=>'Menu',));

These few lines of code create a new Menu widget area on the Widgets page on your Dashboard. You can drag the Custom Menu widget into the Menu widget to indicate that you want to display a custom menu in that area. Figure 6-3 shows the Menu widget area with the Custom Menu widget added.

9781118383339-fg060603.eps

Figure 6-3: Widgets page displaying a Menu widget area with a Custom Menu widget.

To add the widget area to your theme, open the Theme Editor (click the Editor link on the Appearance menu), open the header.php file, and add these lines of code in the area in which you want to display the Menu widget:

<ul>

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Menu') ) : ?>

<?php endif; ?>

</ul>

These lines of code tell WordPress that you want information contained in the Menu widget area to display on your site.

Adding support for custom post types

Custom post types and custom taxonomies have expanded the CMS capabilities of WordPress and are likely to become a big part of plugin and theme features as more developers become familiar with their use. Custom post types allow you to create new content types separate from posts and pages, such as movie reviews or recipes. Custom taxonomies allow you to create new types of content grouping separate from categories and tags, such as genres for movie reviews or seasons for recipes.

Posts and pages are nice generic containers of content. A page is timeless content that has a hierarchal structure — a page can have a parent (forming a nested, or hierarchal, structure of pages). A post is content that is listed in linear (not hierarchal) order based on when it was published and organized into categories and tags. What happens when you want a hybrid of these features? What if you want content that doesn’t show up in the post listings, displays the posting date, and doesn’t have either categories or tags? Custom post types are created to satisfy this desire to customize content types.

By default, WordPress already has different post types built in to the software, ready for you to use. The default post types include

check Blog posts

check Pages

check Menus

check Attachments

check Revisions

Custom post types give you the ability to create new and useful types of content on your website, including a smart and easy way to publish those content types to your site.

The possibilities for the use of custom post types are endless. To kick-start your imagination, here are some of the more popular and useful ideas that others have implemented on sites:

check Photo gallery

check Podcast or video

check Book reviews

check Coupons and special offers

check Events calendar

Core custom post type function

To create and use custom post types on your site, you need to be sure that your WordPress theme contains the correct code and functions. The following steps create a very basic and generic custom post type called Generic Content. Follow these steps to create the same basic custom post type:

1. Open the Theme Functions template file (functions.php).

Click the Editor link on the Appearance menu to open the Theme Editor page. Then click the Theme Functions template link to open the functions.php file in the text editor.

2. Add the custom post types code to the bottom of the Theme Functions template file.

Scroll to the bottom of the functions.php file and include the following code to add a Generic Content custom post type to your site:

// ADD CUSTOM POST TYPE

add_action( 'init', 'create_post_type' );

function create_post_type() {

  register_post_type( 'generic-content',

    array(

      'labels' => array(

        'name' => __( 'Generic Content' ),

        'singular_name' => __( 'Generic Content' )

      ),

      'public' => true

    )

  );

}

3. Click the Update File button to save the changes made to the functions.php file.

The register_post_type function can accept several arguments and parameters, which are detailed in Table 6-3. You can use a variety and combination of different arguments and parameters to create a specific post type. You can find more information on Custom Post Types and using the register_post_type function in the WordPress Codex at

http://codex.wordpress.org/Function_Reference/register_post_type

tip.eps If you really don't feel up to writing this code in the Theme Functions template file, check out a nifty plugin developed for WordPress called Custom Post Types UI, written by Brad Williams of WebDevStudios (http://webdevstudios.com). This plugin provides you with an interface in your WordPress Dashboard that simplifies the creation of custom post types on your site and completely bypasses the need to create the code in the Theme Functions template file (functions.php). You can find the plugin at

http://wordpress.org/extend/plugins/custom-post-type-ui

After you complete the steps to add the generic content post type to your site, the Generic Content post type appears on the left navigation menu on the Dashboard, as shown in Figure 6-4.

9781118383339-fg060604.tif

Figure 6-4: A new custom post type menu appears on the Dashboard.

You add and publish new content by using the new custom post type the same way you do when you write and publish blog posts. The published content isn’t added to the chronological listing of blog posts; it’s treated as separate content, just like static pages.

Generic Content is part of the permalink structure, and the permalink looks similar to http://yourdomain.com/generic-content/new-article.

9781118383339-tb060603a.png

9781118383339-tb060603b.png

9781118383339-tb060603c.png

9781118383339-tb060603d.png

9781118383339-tb060603e.png

Listing 6-2 shows you the code for the No Rules Theatre website. The custom post type called Shows creates custom content for the shows that the theatre produces each season. Reference the parameters and information provided in Table 6-3 while reading the lines of code in Listing 6-2 to see how the custom post types for the No Rules Theatre site were created and applied.

tip.eps Go to http://norulestheatre.org to see custom content in action.

Listing 6-2: Custom Post Type Example

// ADD CUSTOM POST TYPE: SHOWS

add_action( 'init', 'create_my_post_types' );

function create_my_post_types() {

....register_post_type( 'shows',

....array(

....'labels' => array(

....'name' => __( 'Shows' ),

....'singular_name' => __( 'Show' ),

....'add_new' => __( 'Add New Show' ),

....'add_new_item' => __( 'Add New Show' ),

....'edit' => __( 'Edit' ),

....'edit_item' => __( 'Edit Show' ),

....'new_item' => __( 'New Show' ),

....'view' => __( 'View Show' ),

....'view_item' => __( 'View Show' ),

....'search_items' => __( 'Search Shows' ),

....'not_found' => __( 'No shows found' ),

....'not_found_in_trash' => __( 'No shows found in Trash' ),

....'parent' => __( 'Parent Show' ),

....),

 

....'public' => true,

....'show_ui' => true,

....'publicly_queryable' => true,

....'exclude_from_search' => false,

....'menu_position' => 10,

....'menu_icon' => get_stylesheet_directory_uri() . '/img/nrt-shows.png',

....'hierarchical' => true,

....'query_var' => true,

....'rewrite' => array( 'slug' => 'shows', 'with_front' => false ),

....'taxonomies' => array( 'post_tag', 'category'),

....'can_export' => true,

....'supports' => array(

....'post-thumbnails',

....'excerpts',

....'comments',

....'revisions',

....'title',

....'editor',

....'page-attributes',

....'custom-fields')

....)

....);

}

tip.eps The three modules WordPress gives you to add menus from are Custom Links, Pages, and Categories. On the Custom Menu page in the WordPress Dashboard, click the Screen Options tab at the top right of that page; the check box next to Post Types enables your custom post types in the Menus you create.

Custom post type templates

By default, custom post types use the single.php template in your theme — that is, they do unless you create a specific template for your custom post type if you find the regular WordPress single.php template too limiting for your post type.

The preceding section has the code to build a simple Generic Content custom post. After that is added, a Generic Content menu appears on the WordPress Dashboard. Click the Add New link on the Generic Content menu and publish a new post to add some content for testing. In this example, a new Generic Content type with a title of Test and a slug of test is added. Because the Generic Content type doesn't have a specific template, it uses the single.php template, and resulting posts look no different from a standard one.

tip.eps If you get a Not Found page when you try to go to a new custom post type entry, reset your permalink settings. Click the Permalinks link on the Settings menu on the WordPress Dashboard and then click the Save Changes button. WordPress resets the permalinks, which adds the new custom post type link formats in the process.

To build a template specific for the Generic Content post type, add a new template named single-posttype.php where posttype is the first argument passed to the register_post_type function from the preceding section. For this example, the single template file specific to Sample Post Type is single-generic-content.php. Any modifications made to this template file appear only for instances of the Generic Content post type.

Tying this together with the section on template parts from earlier in this chapter, a basic structure for single-generic-content.php for the Twenty Twelve theme is

<?php get_header(); ?>

<div id="container">

    <div id="content" role="main">

        <?php get_template_part('loop', 'generic-content'), ?>

    </div><!-- #content -->

</div><!-- #container -->

<?php get_sidebar(); ?>

<?php get_footer(); ?>

By using the template part, creating a file called loop-generic-content.php allows for easy customization of The Loop for the Generic Content post type entry.

Adding support for custom taxonomies

Similar to how having posts and pages as content options can be limiting, sometimes categories and tags just aren’t enough. The example of a movie review custom post type might need a variety of new taxonomies or grouping options. Organizing movie reviews by director, movie star, review rating, film genre, and MPAA rating allows visitors to the site to view different groupings of reviews that might interest them. Like the custom post type example, this example creates a very simple taxonomy to test custom taxonomy–specific templates. For this example, a new post taxonomy called Sample Taxonomy is created.

To register this new taxonomy, use the register_taxonomy function. Adding the following code to the bottom of your theme's functions.php file registers the new sample taxonomy custom taxonomy specifically for WordPress built-in posts, adds a Sample Taxonomy link to the Posts menu entry to manage the Sample Taxonomy entries, and adds sample taxonomy options to the editor for posts.

register_taxonomy( 'sample-taxonomy', 'post', array( 'label' => 'Sample Taxonomy' ) );

This function call gives the new custom taxonomy an internal name of sample-taxonomy, assigns the new taxonomy to Posts, and gives the taxonomy a human-readable name of Sample Taxonomy.

After adding this code to your theme, you can create and assign Sample Taxonomies when creating a new post or editing an existing post. For this example, you could add a sample taxonomy with a name of Testing to an existing post and update the post.

With the Testing taxonomy added, you can now visit example.com/sample-taxonomy/testing to get the archive page for the new sample taxonomy.

tip.eps If you get a Not Found page or you don’t get an archive listing when you try to go to a specific sample taxonomy entry’s archive, resave your permalink settings. Click the Permalinks link on the Settings menu on the WordPress Dashboard and then click Save Changes. This forces WordPress to reset the permalinks, which adds the new custom taxonomy link formats in the process.

Adding a new template file called taxonomy-sample-taxonomy.php allows for adding a template specific to this new custom taxonomy. Like you can with categories and tags, you can add a template that is specific to a single custom taxonomy entry. Therefore, a template specific to a sample taxonomy with a slug of testing would have a filename of taxonomy-sample-taxonomy-testing.php.

remember.eps Custom taxonomies is a feature that will appeal to only a specific type of site that deals mainly in niche areas of content: Sites that want to really drill down navigation and grouping options for their content. You can find more about custom taxonomies in the WordPress Codex at

http://codex.wordpress.org/Function_Reference/register_taxonomy

Adding support for post formats

Introduced in version 3.1 of WordPress, the Post Formats feature allows you to designate a different content display and style for certain types of designated posts. Unlike custom post types, you aren’t able to create different post formats because WordPress has already assigned them for you — it’s up to you what post format, if any, you want to use in your theme.

Here are the nine types of WordPress post formats:

check Aside: A very short post that shares a random thought or idea. Typically, an aside is shared without a post title or any category/tag designations; it’s simply a random, one-off thought — not a full post — shared on your blog.

check Audio: A post that shares audio files or podcasts. Usually, audio posts have very little text and include a built-in audio player so visitors can click and listen.

check Chat: A transcript of an online conversation that can be formatted to look like a chat (or Instant Message) window.

check Gallery: A gallery of clickable images, where clicking an image opens a larger version of the photo. Often, galleries don’t contain text (but may have a title) and are used for only the display of a gallery.

check Image: A post that shares a single image. The image may or may not have text or a caption to go with the post.

check Link: A post that provides a link you find useful and want to share with your readers. These post formats often contain a title and, sometimes, a short bit of text that describes the link.

check Quote: A post that displays a quotation on your blog. Often, users will include a byline or the quote’s source.

check Status: A short status update, usually limited to 140 characters or less. (Think Twitter!)

check Video: A post that displays a video, usually embedded within a video player (say YouTube) so your readers can play the video without leaving your site.

This list of post format types is all there is; you only have nine designated post formats. You can use one or all of them in your theme, depending on your specific needs.

Figure 6-5 shows you how post formats work. They cleanly separate the formats in the menu navigation and in the individual post styling and icons used to designate the formats.

9781118383339-fg060605.tif

Figure 6-5: Post formats.

tip.eps If you find that your site needs a different type of post format that is not currently available, consider adding it as a custom post type.

Core post format function

To add support for post formats in your theme, you need to add the core function call to your Theme Functions template file (functions.php). After you follow these few steps to make it happen, you'll see the magic that occurs on the Add New Post page on your WordPress Dashboard! Here's how to add post formats support in your theme:

1. Click the Editor link on the Appearance menu on your Dashboard.

The Edit Themes page appears.

2. Open the Themes Function file in the text editor.

The link for the Theme Functions template file is on the right side of the Edit Themes page. Clicking this link opens the Theme Functions template file (functions.php) in the text editor on the left side of the Edit Themes page.

3. Add the following function on a new line:

add_theme_support( 'post-formats', array( 'aside', 'chat', 'gallery', 'image', 'link', 'quote', 'status', 'video', 'audio' ) );

tip.eps This code sample adds all nine post formats to the theme. You don’t have to use all nine; you can include only the formats that you need in your theme and leave the rest.

4. Click the Update File button to save the changes made to the functions.php file.

You won’t notice an immediate change to your site when you save your new Theme Functions template file with the Post Formats support added. To see what WordPress added to your site, you need to visit the Add New Post page (which you access by clicking the Add New link on the Posts menu).

The change is subtle, but if you follow the steps to add post format support, you see a Format item in the Publish module on the right side of the page, as shown in Figure 6-6. Click the Edit link to the right of Format to designate a format for your post. In Figure 6-6, see all nine post format options listed. You also see a tenth format option, Standard (or Default), which is used when you don’t select a specific format for your post.

9781118383339-fg060606.tif

Figure 6-6: The Format option on the Add New Post page.



Template tags for post formats

Adding Post Format support to your theme isn’t enough. If you’re going to add post format support, you really should provide some unique styling for each type of format; otherwise, your post formats will look like your blog posts and the point of adding them to your theme will be lost.

You can display your post format two ways:

check Content: For each format, you can designate what content you want to display. For example, if you don’t want to display a title for your Asides format, you leave out the template tag that calls it but leave the tag in for your Video post format.

check Style: Utilizing the HTML markup that is provided by the post_class(); tag, your formats each have a CSS class assigned to them. Use those CSS classes to provide unique styles for fonts, colors, backgrounds, and borders to each of your post formats. The nearby "Post class defined" sidebar discusses how to use HTML and CSS to create custom styles in your template.

Adding unique styles for your post formats starts with creating the content designations you want to display for each format. Earlier in this section is a list of nine post formats and some ideas on what you can do to display them on your site. The possibilities are endless, and it's really up to you. Refer to Chapter 3 of this minibook for more information on the content-related template tags you can use in these areas. The following steps take you through the creation of a very simple, stripped-down Main Index file (index.php):

1. Open your favorite text editor, such as Notepad (for PC) or TextMate (for Mac).

2. Type <?php get_header(); ?>.

This function includes all the code from your theme's header.php file.

3. Type the following two lines:

<?php if (have_posts()) : ?>

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

These two lines of code indicate the beginning of The Loop (discussed in Chapter 3 of this minibook).

4. Type <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>.

This line provides HTML and CSS markup, using the post_class(); function that provides you with unique CSS classes for each of your post formats. (See the "Post class defined" sidebar.)

5. Type <?php.

This part initiates the start of a PHP function.

6. Type the following lines to provide content for the Asides post format:

if ( has_post_format( 'aside' )) {

echo the_content();

}

7. Type the following lines to provide content for the Gallery post format:

elseif ( has_post_format( 'gallery' )) {

echo '<h3>';

echo the_title();

echo '</h3>';

echo the_content();

}

8. Type the following lines to provide content for the Image post format:

elseif ( has_post_format( 'image' )) {

echo '<h3>';

echo the_title();

echo '</h3>';

echo the_post_thumbnail('image-format'),

echo the_content();

}

9. Type the following lines to provide content for the Link post format:

elseif ( has_post_format( 'link' )) {

echo '<h3>';

echo the_title();

echo '</h3>';

echo the_content();

}

10. Type the following lines to provide content for the Quote post format:

elseif ( has_post_format( 'quote' )) {

echo the_content();

}

11. Type the following lines to provide content for the Status post format:

elseif ( has_post_format( 'status' )) {

echo the_content();

}

12. Type the following lines to provide content for the Video post format:

elseif ( has_post_format( 'video' )) {

echo '<h3>';

echo the_title();

echo '</h3>';

echo the_content();

}

13. Type the following lines to provide content for the Audio post format:

elseif ( has_post_format( 'audio' )) {

echo '<h3>';

echo the_title();

echo '</h3>';

echo the_content();

}

14. Type the following lines to provide content for all other (Default) posts:

else {

echo '<h3>';

echo the_title();

echo '</h3>';

echo the_content();

}

15. Type ?>.

This line ends the PHP function.

16. Type </div>.

This closes the HTML div tag opened in Step 4.

17. Type <?php endwhile; else: ?> <?php endif; ?>.

This closes the endwhile and if statements that were opened in Step 3.

18. Type <?php get_sidebar(); ?>.

This function calls in the code included in the sidebar.php file of your theme.

19. Type <?php get_footer(); ?>.

This function calls in the code included in the footer.php file of your theme.

20. Save your file as index.php.

Upload it into your theme folder, replacing your existing index.php file.

Listing 6-3 displays the full code for your new index.php file.

Listing 6-3: A Simple Post Formats Template

<?php get_header(); ?>

<?php if (have_posts()) : ?>

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

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

<?php

 

if ( has_post_format( 'aside' )) {

....echo the_content();

}

 

elseif ( has_post_format( 'gallery' )) {

....echo '<h3>';

....echo the_title();

....echo '</h3>';

....echo the_content();

}

 

elseif ( has_post_format( 'gallery' )) {

....echo '<h3>';

....echo the_title();

....echo '</h3>';

....echo the_content();

}

 

elseif ( has_post_format( 'image' )) {

....echo '<h3>';

....echo the_title();

....echo '</h3>';

....echo the_post_thumbnail('image-format'),

....echo the_content();

}

 

elseif ( has_post_format( 'link' )) {

....echo '<h3>';

....echo the_title();

....echo '</h3>';

....echo the_content();

}

 

elseif ( has_post_format( 'quote' )) {

....echo the_content();

}

 

elseif ( has_post_format( 'status' )) {

....echo the_content();

}

 

elseif ( has_post_format( 'video' )) {

....echo '<h3>';

....echo the_title();

....echo '</h3>';

....echo the_content();

}

 

elseif ( has_post_format( 'audio' )) {

....echo '<h3>';

....echo the_title();

....echo '</h3>';

....echo the_content();

}

 

else {

....echo '<h3>';

....echo the_title();

....echo '</h3>';

....echo the_content();

}

?>

</div>

<?php endwhile; else: ?>

<?php endif; ?>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

The example in Listing 6-3 is a very simple one and doesn't include a whole lot of HTML markup or CSS classes. Therefore, you can focus on the code bits that are required to designate and define different content displays for your post formats. You can see, in Listing 6-3, that some of the formats contain the template tag to display the title, the_title();, and others do not — but they all contain the template tag to display the content of the post: the_content();. As I mention previously, you can play with different content types and markup that you want to add to your post formats.

By coupling your template additions for post formats with the post_class(); tag that adds special CSS classes and markup for each post format type, you can customize the display of each post format to your heart's content.

Adding support for post thumbnails

The WordPress feature called Post Thumbnails (also known as Featured Images) takes a lot of the work out of associating an image with a post and using the correct size each time. A popular way to display content in WordPress themes includes a thumbnail image with a short snippet (excerpt) of text — the thumbnail images are consistent in size and placement within your theme. Prior to the inclusion of post thumbnails in WordPress, users would have to open their image in an image editing program (such as Photoshop) and crop and resize their image to the desired size; or use fancy scripts that would resize images on the fly, which tend to be resource intensive on web servers, so it wasn’t an optimal solution. How about a content management system that will crop and resize your images for you to the exact dimensions that you specify? Yep, WordPress does that for you with just a few adjustments.

By default, when you upload an image, WordPress creates three versions of your image based on dimensions that are set on your Dashboard (click the Media link on the Settings menu):

check Thumbnail size: Default dimensions are 150px x 150px

check Medium size: Default dimensions are 300px x 300px

check Large size: Default dimensions are 1024px x 1024px

Therefore, when you upload an image, you actually end up with four sizes of that image stored on your web server: thumbnail, medium, large, and the original image. Images are cropped and resized proportionally, and when you use them in your posts you can typically designate which size you would like to use in the image options of the uploader. (See Book IV, Chapter 3 for a refresher on uploading images in WordPress.)

Within the WordPress image uploader, you can designate a particular image as the featured image of the post, and then, using the Featured Images function that you add to your theme, you can include template tags to display your chosen featured image with your post. This is helpful for creating magazine- or news-style themes that are popular with WordPress sites. Figure 6-7 shows how post thumbnails and featured images display a thumbnail associated with each post excerpt.

Also covered in the following sections is adding support for different image sizes, other than the default image sizes that are set on the Media Settings page of your Dashboard. This is helpful when you have sections of your site where you want to display a much smaller thumbnail, or a larger version of the medium-sized thumbnail that’s not as big as the large size.

9781118383339-fg060607.tif

Figure 6-7: Post thumbnails in use.

Core post thumbnails function and template tag

Adding support for post thumbnails includes one line of code added to your Theme Functions template file (functions.php):

add_theme_support( 'post-thumbnails' );

After you add this line of code to your Theme Functions template file, you can use the Featured Image feature for your posts. You can designate featured images by using the function in the WordPress image uploader. The function is also an option on the Add New Post page, where you write and publish your posts.

After you add featured images to your posts, make sure that you add the correct tag in your template(s) so the featured images display on your site in the area you want them to display. Open your index.php template, and include the following line of code to include the default thumbnail-size version of your chosen featured image in your posts:

<?php if ( has_post_thumbnail() ) { the_post_thumbnail('thumbnail'), ?>

The first part of that line of code checks whether a featured image is associated with the post. If there is, the image displays; if a featured image doesn’t exist for the post, the code returns nothing. You can also include the other default image sizes (set in your Media Settings page in the Dashboard, as shown in Figure 6-8) for medium-, large-, and full-sized images by using these tags:

<?php if ( has_post_thumbnail() ) { the_post_thumbnail('medium'), ?>

<?php if ( has_post_thumbnail() ) { the_post_thumbnail('large'), ?>

<?php if ( has_post_thumbnail() ) { the_post_thumbnail('full'), ?>

9781118383339-fg060608.tif

Figure 6-8: The Media Settings page on the Dashboard.

Adding custom image sizes for post thumbnails

If the predefined, default image sizes in WordPress (thumbnail, medium, large, and full) don't satisfy you, and there's an area on your site that you want to display images with dimensions that vary from the default, WordPress makes it relatively easy to add custom image sizes in your Theme Functions template file. You then use the the_post_thumbnail function to display it in your theme.

You are not limited on what sizes you can add for your images, and this example shows how to add a new image size of 600px x 300px. Add this line to your Theme Functions template file (functions.php) beneath the add_theme_support('post-thumbnails') function you added:

add_image_size( 'custom', 600, 300, true);

This code tells WordPress that it needs to create an additional version of the images you upload, and to crop and resize it to the dimensions of 600px x 300px. Notice the four parameters in the add_image_size function:

check Name ($name): Gives the image size a unique name that you can use in your template tag. For example, the image size in this example uses the name 'custom'.

check Width ($width): Gives the image size a width dimension in numbers. In this example, the width is defined as '600'.

check Height ($height): Gives the image size a height dimension in numbers. In this example, the height is defined as '300'.

check Crop ($crop): This parameter is optional and tells WordPress whether it should crop the image to exact dimensions or do a soft proportional resizing of the image. In this example, the parameter is set to 'true' (accepted arguments: true or false).

Adding the custom image size to your template to display the featured image is the same as adding default image sizes. The only difference is the name of the image set in the parentheses of the template tag. The custom image size in this example uses the following tag:

<?php if ( has_post_thumbnail() ) { the_post_thumbnail('custom'), ?>

Exploring Theme Options

One of the key features of an advanced theme is a Theme Options page. A Theme Options page allows the theme user to supply information to the theme without having to modify the theme files. Although a single-use theme could have this information hard-coded into the theme, it’s an inelegant solution. If the theme is used more than once or is managed by a non-developer, having an easy-to-change setting on the back end allows changes to be made quickly and easily.

Use a Theme Options page when the information is specific to the user and not the theme design. Web analytics code (such as visitor tracking JavaScript from Google Analytics or Woopra) is a good example of this user-specific information. Because hundreds of analytics providers exist, most analytics providers require the JavaScript code to be customized for the specific site. The theme could have a number of different header and footer files, providing easy-to-use theme options. Adding JavaScript code to the header and the footer rather than requiring theme file modifications can make using your theme much easier.

tip.eps Early in the design process, consider what a user may want to modify. Advanced uses of a Theme Options page vary widely and include design editors, color pickers, font options, and settings to modify the theme layout (switch a sidebar from one side of the theme to another, for example). The options offered depend on the project and the design.

Understanding theme options basics

Before jumping into the code, you should understand some basic concepts of how theme options work.

Before WordPress version 2.8, adding options to your theme required the developer to code the entire process, including providing an input form to accept the options, storing the options in the database, and retrieving the options from the database to use them. Fortunately, things have gotten much better. Some work is still required, but adding options is much easier now.

To let the user access the theme options, an input form is required. This process requires the most work because the form still needs to be manually created and managed. The form will need to be added to the back end so the user can access it. Adding a new option to the Appearance menu allows the user to find the Theme Options page. Fortunately, WordPress offers an easy-to-use function called add_theme_page. To have WordPress manage as much as possible for you, the code will need to tell WordPress to store the data. The register_setting function can handle this.

Building a simple theme options page

Now that you know what pieces you need to build the Theme Options page, you can jump into the code. Open a plain-text editor and enter the code in Listing 6-4.

Listing 6-4: The Theme Options Page

<?php

function cm_theme_options_init() →2

register_setting( 'cm_theme_options', 'theme_options' ); →3

}

add_action( 'admin_init', 'cm_theme_options_init' ); →5

function cm_theme_options_menu() { →6

add_theme_page( 'Theme Options', 'Theme Options', 'manage_options', 'cm_theme_options', 'cm_theme_options_page' ); →7

}

add_action( 'admin_menu', 'cm_theme_options_menu' ); →9

function cm_theme_options_page() { →10

?>

<div class="wrap"> →12

<?php screen_icon(); ?> →13

<h2>Theme Options</h2> →14

<form method="post" action="options.php"> →15

<?php settings_fields( 'cm_theme_options' ); ?> →16

<?php $options = get_option( 'theme_options' ); ?> →17

<table class="form-table"> →18

<tr valign="top"> →19

<th scope="row">Checkbox</th> →20

<td><input name="theme_options[checkbox]" type="checkbox" value="1" <?php checked('1', $options['checkbox']); ?> /></td> →21

</tr>

<tr valign="top"><th scope="row">Text</th> →23

<td><input type="text" name="theme_options[text]" value="<?php echo $options['text']; ?>" /></td> →24

</tr>

<tr valign="top"> →26

<th scope="row">Text Area</th> →27

<td><textarea name="theme_options[text_area]"><?php echo $options['text_area']; ?></textarea></td> →28

</tr>

</table>

<p class="submit"><input type="submit" class="button-primary" value="<?php _e( 'Save Changes' ); ?>" /></p> →31

</form>

</div>

<?php

}

?>

Here’s a brief explanation of what the various lines do:

2 This creates a new function that calls register_setting, the function that tells WordPress about the need to store data.

3 This tells WordPress that you're creating a new settings group called cm_theme_options. The theme_options argument sets the WordPress options name used to store and retrieve the theme options. You'll want to change these to be unique to your theme so that you don't accidentally load or save over settings from other themes or plugins.

5 The new cm_theme_options_init function needs to be called to work. This line causes the function to be called during the admin_init action, which is a good action to use to run functions that need to be called on each admin page load.

6 This new function handles registering the new menu entry that will show your form.

7 The add_theme_page function adds a new menu entry under the Appearance menu. In order, the arguments are page title (shows in the title bar of the browser), menu entry name, required access level to visit the page, the variable name of the page (this needs to be unique for the page to work), and the function that should be run when visiting the menu location. This last argument (cm_theme_options_page in the example) is the name of the function that holds the options form.

9 The new cm_theme_options_menu function needs to be called to work. This line causes the function to be called during the admin_menu action, which is when new menu entries should be added.

10 This new function produces the input form for editing the theme options.

12 Wrapping a form in the wrap class applies WordPress's default formatting.

13 This outputs the Appearance icon in front of the heading that follows.

14 This adds a title to the theme options page.

15 Starts the HTML form with an action that points to options.php and handles saving the data.

16 The settings_fields adds some hidden inputs that allow the options to save properly. The cm_theme_options argument must match the first argument passed to the register_setting function. If this function is missing or if the argument doesn't match the first argument of the register_setting function, the options won't save properly.

17 This line loads the saved theme options into the $options variable. The theme_options argument must match the second argument passed to the register_setting function.

18 Giving the table a class of form-table applies WordPress's default form styling.

19–20 Starts a new row to hold the first option and adds a description row header (the content inside the th tag). As indicated by the description, this option will be a generic check box input.

21 Adds the check box input. The checked function from WordPress handles outputting the required HTML if a checked state was previously saved. The theme_options[checkbox] portion matches the second argument passed to the register_setting function followed by the name of the specific option (in this case, checkbox). The $options['checkbox'] loads the specific option from the $options array.

23 Starts a new row to hold another option and adds a description row header (the content inside the th tag). As indicated by the description, this option will be a generic text input.

24 Adds the text input. The echo outputs the existing value so that it pre-populates the input. The theme_options[text] portion matches the second argument passed to the register_setting function followed by the name of the specific option (in this case, text). The $options['text'] loads the specific option from the $options array.

26–27 Starts a new row to hold another option and adds a description row header (the content inside the th tag). As indicated by the description, this option will be a generic text area input.

28 Adds the text area input. The echo outputs the existing value so that it pre-populates the input. The theme_options[text_area] portion matches the second argument passed to the register_setting function followed by the name of the specific option (in this case, text_area). The $options['text_area'] loads the specific option from the $options array.

31 Adds a button with a description of Save Changes. Giving the input a class of button-primary and wrapping it in a p tag with a class of submit applies WordPress's default button styling.

To load this file, you need to add a line of code to the theme's functions.php file. Edit the functions.php file and add the following line at the bottom of the file:

require_once( 'theme-options.php' );

Click the Themes Option link on the Appearance menu. The Theme Options page appears, as shown in Figure 6-9.

Using theme options in the theme

Compared with setting up a theme options page, using the stored options is very easy. To make it easier, add the following code — a quick function that makes using the options as simple as a single function call — to your theme's functions.php file:

<?php

function get_theme_option( $option_name ) {

    global $theme_options;

        if ( ! isset( $theme_options ) )

            $theme_options = get_option( 'theme_options' );

        if ( isset( $theme_options[$option_name] ) )

            return $theme_options[$option_name];

    return '';

}

?>

9781118383339-fg060609.tif

Figure 6-9: The new Theme Options page in the WordPress back end.

The get_theme_option function takes an option name as its only argument and returns that option's value. For example, to get the check box option value, simply call get_theme_option('checkbox').

If your theme has a section that can be enabled and disabled by a theme option check box, a section of code such as the following works very well:

<?php if ( get_theme_option('checkbox') ) : ?>

    <!-- example code -->

<?php endif; ?>

Typically, text or text area options output user-provided content. By using a check to see whether an option has a value, your theme can offer a default set of text that can be overridden by text entered into a theme option:

<div class="footer-right">

    <?php if ( get_theme_option('text') ) : ?>

        <?php echo get_theme_option('text'), ?>

    <?php else : ?>

        <p>Sample Theme by Lisa Sabin-Wilson</p>

    <?php endif; ?>

    <p>Powered by <a

href="http://wordpress.org">WordPress</a></p>

</div>

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

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