Advanced WordPress Themes

Exclusive offer: get 50% off this eBook here
WordPress 2.8 Themes Cookbook

WordPress 2.8 Themes Cookbook — Save 50%

Over 100 simple but incredibly effective recipes for creating powerful, custom WordPress themes

$23.99    $12.00
by Lee Jordan Nick Ohrn | June 2010 | Content Management Open Source Web Development WordPress

In this article by Lee Jordan and Nick Ohrn, authors of the book WordPress 2.8 Themes Cookbook, we will cover:

  • Adding a theme options page
  • Allowing for multiple theme color schemes
  • Changing the default Gravatar icon for your theme

(For more resources on Wordpress, see here.)

Creating a basic WordPress theme is great. You learn about The Loop, find the appropriate template tags to display the information that you want, and then you write some HTML and CSS to tie it all together. However, there comes a time when you're ready to take your themes to the next level. That is what this article is all about.

In this article, you'll learn how to provide your theme's users with options about what is displayed and how it is displayed. You'll also learn about localizing your theme for an international audience and showing users information based on their current role.

Finally, this article covers the essentials for packaging and distributing your theme via the WordPress.org theme repository. You'll need to follow a few simple steps to make sure that your theme is accepted and that it provides users with the best possible experience.

Adding a theme options page

As a theme developer, you have to make a lot of choices when you create a theme. What text should be displayed in certain locations? Will that text always be appropriate? How many posts should you display in a featured item carousel? How many levels should the nested navigation menu have?

Part of being a good developer is knowing when to make these decisions for your theme's users, and when to give the users a choice. Many WordPress users are not comfortable with editing PHP files, so you need to provide some other way for users to make these choices. The best way, in the context of a WordPress theme, is to provide the users with a theme options panel.

Getting started

You need to have created a WordPress theme containing at least a style.css file and an index.php file.

How to do it...

First, you need to decide what choice you want to give your users. In this recipe, we're going to assume that you want users to be able to change the color of the name of their site, which is located in the site header.

Next, you have to create the options page that lets users make their choice and save it. Open your theme's directory and create a new directory inside it called admin. Inside the admin directory, create a file called options.php.

Open the options.php file, and insert the following code:

<?php
$settings = $this->get_settings();
?>
<div class="wrap">
<h2><?php _e('My Theme Options' ); ?></h2>
<?php if('1'==$_GET['updated']) { ?>
<div id="my-theme-options-updated" class="updated fade"><p><?php _e(
'Settings saved!' ); ?></p></div>
<?php } ?>
<form method="post">
<table class="form-table">
<tbody>
<tr>
<th scope="row"><label for="custom-theme-header-color">
<?php _e('Header Color'); ?></label></th>
<td>
#<input type="text" class="regular-text"
name="custom-theme-header-color"
id="custom-theme-header-color"
value="<?php echo esc_attr( $settings[
'header-color' ] ); ?>" />
</td>
</tr>
</tbody>
</table>
<p class="submit">
<?php wp_nonce_field( 'custom-theme-save-options' ); ?>
<input type="submit" class="button-primary"
name="custom-theme-save-options"
id="custom-theme-save-options"
value="<?php _e( 'Save' ); ?>" />
</p>
</form>
</div>

This file contains all of the code necessary for the theme options page.

The next thing that you need to do is to hook the admin page into the WordPress administrative menu. Open or create your theme's functions.php file and insert the following code:

if (!class_exists('My_Theme')) {
class My_Theme {
var $settings = null;
function My_Theme() {
add_action('admin_init', array(&$this, 'save_settings'));
add_action('admin_menu', array(&$this, 'add_admin_stuff'));
}

function add_admin_stuff() {
add_theme_page(__('My Theme'), __('My Theme'),
'switch_themes', 'my-theme', array(&$this,
'display_theme_admin_page'));
}

function display_theme_admin_page() {
include (TEMPLATEPATH.'/admin/options.php');
}
function save_settings() {
if (isset($_POST['custom-theme-save-options']) &&
check_admin_referer('custom-theme-save-options') && current_user_
can('switch_themes')) {
$settings = $this->get_settings();
$settings['header-color'] = stripslashes($_
POST['custom-theme-header-color']);
$this->set_settings($settings);
wp_redirect(admin_url('themes.php?page=my-
theme&updated=1'));
}
}

function get_settings() {
if (null === $this->settings) {
$this->settings = get_option('My Theme Custom
Settings', array());
}
return $this->settings;
}

function set_settings($settings) {
if (is_array($settings)) {
$this->settings = $settings;
update_option('My Theme Custom Settings', $this-
>settings);
}
}

}

$my_theme = new My_Theme();
function get_custom_theme_header_color() {
global $my_theme;
$settings = $my_theme->get_settings();
$color = $settings['header-color'];
if(empty($color)) {
$color = '000000';
}
return $color;
}
function the_custom_theme_header_color() {
echo get_custom_theme_header_color();
}
}

This file hooks into two different WordPress administrative hooks. First, you add the administrative menu page by hooking into admin_menu. Then, you hook to admin_init to process and save the custom options present on the custom admin page.

After you save these files, go to your administrative menu and look at the sidebar on the left-hand side under the Appearance heading. You should see a My Theme link, as shown in the following screenshot:

Advanced WordPress Themes

Now, click on the My Theme link under the Appearance menu heading. If you've done everything correctly, you should see a page that looks like the following screenshot:

Advanced WordPress Themes

Enter a value such as 99000 and click on the Save button, and you'll see a Settings saved! success message, as seen in the following screenshot:

Advanced WordPress Themes

Now, you need to use your custom value somewhere in your theme. Open up your theme header (usually header.php or index.php) and insert the following code between the opening and closing <head> tags:

<h1 style="color:#<?php the_custom_theme_header_color(); ?>;"><?php
bloginfo(); ?></h1>

View your site in a browser to see the change in color of the site title (this is usually the only text that uses the <h1> tag) with the custom option set to hexadecimal color value 990000:

Advanced WordPress Themes

Now, whatever value you set for the custom option that we created will be used as the color for the site title.

How it works...

There are quite a few moving parts here, so let's go through them one by one. First, you created the administrative page. This was saved to /yourthemefolder/admin/options.php. This file contains all of the items contained on a typical WordPress admin page:

  • A containing <div> with the wrap class
  • A <h2> tag with the custom theme options title
  • A form that posts back to itself
  • Form elements arranged inside a <table> with the form-table class

With all of these elements in place, you get a slick looking administrative page that blends in with the rest of the WordPress admin control panel.

Next, you created a small script within the functions.php file that hooks the administrative menu into place and saves the options when the page is posted. You hooked to admin_menu to add the administrative page and admin_init to save the options using the WordPress add_action() function that accepts a key value pair of the named action as a descriptive string and the actual action to take place. Your custom options are saved when three conditions are met:

  1. The form posts back to itself.
  2. The system verifies the security nonce from the form.
  3. The currently logged-in user has the ability to switch themes (usually just the blog administrator).

The options are saved as an array to the WordPress options table by using the update_ option function. When you need to retrieve the options, you call get_option and pass the appropriate key.

In addition to the hooks that provide the core functionality of this script, you created two template tags. The tag the_custom_theme_header_color() allowed you to access, and get_custom_theme_header_color() allowed you to print the values you stored on the custom options page.

Finally, you used the template tags that you created to take advantage of your custom option on the front-end by adding <?php _the_custom_theme_header_color(); ?>; to the style of the <h1> tag that controls the color and size of the blog title. In this particular instance, you're allowing your theme's users to modify the color of the theme's header. However, endless possibilities exist as you become more familiar with WordPress, and by expanding the options, you allow your users to modify your themes.

There's more…

You can add additional theme option settings to customize how users can edit your theme.

Diving into administrative settings for themes

Visit the WordPress codex at http://codex.wordpress.org/Function_Reference to learn more about the functions available to you for creating custom theme edit forms in the administrative area of WordPress.

Allowing for multiple theme color schemes

In the previous recipe, we covered the general way in which you provide your theme's users with an options page. In this recipe, you'll implement one of the most straightforward features that many premium themes possess: a theme color scheme chooser.

Getting started

You need to have created a WordPress theme containing at least a style.css file and an index.php file. Inside the template file containing your theme's <head> tag, you need to call the wp_head function.

How to do it...

You're going to be controlling the color schemes that users can select, by putting each one in a different CSS file. As such, the first thing that you have to do is to create these files. Open your theme's directory and create a new directory named schemes. Inside the schemes directory, create the files blue.css, red.css, and green.css. They should contain the following styles:

@charset "utf-8";
/* Blue.CSS Color Schemes Document Chapter 11 Example 2 */
body{
color:#00f; /* very bright medium blue*/
background-color:#99ccff; /* light blue*/}
/* theme links*/
a., a:link, a:hover, a:visited {}
a., a:link{color:#000099;} /* medium dark blue*/
a:hover{color: #0066FF;} /* bright medium blue*/
a:visited{color:#000099;}
/* blog title styles*/
h1.blog-title, h1.blog-title a{
color:#000033; /* dark blue*/
text-decoration:none;}

#header a {
color: #000033;
text-decoration: none;
}

#header a:hover {
color: #0066FF;
text-decoration: underline;}

#header a:visited{color:#000099;}

h2{
color:#003399; /* medium blue*/
text-decoration:none;}
#header{
background:none;
font-family:arial, verdana, sans-serif;
}

h2 a {
color:#003399;/* medium blue */
text-decoration:none;}
h3.storytitle, h3.storytitle a{
color:#003399; /* medium blue*/
text-decoration:none;}

@charset "utf-8";
/* Red.CSS Color Schemes Document Chapter 11 Example 2 */
body{
color:#660000; /* dark red */
background-color:#ffffcc; /* light orange-pink*/}
/* theme links*/
a., a:link, a:hover, a:visited {}
a., a:link{color:#ff0000;} /* bright red */
a:hover{color: #ff0033} /* bright pink */
a:visited{color:#ff0000;}
/* blog title styles*/
h1.blog-title, h1.blog-title a{
color:#ff3333; /* medium pink-red*/
text-decoration:none;}
#header a {
color: #ff3333;
text-decoration: none;
}

#header a:hover {
color: #ff0033;
text-decoration: underline;}

#header a:visited{color:#ff3333;}
h2{
color:#660000; /* medium medium dull red*/
text-decoration:none;}
h2 a {
color:#660000; /* medium medium dull red*/
text-decoration:none;}

h3.storytitle, h3.storytitle a{
color:#ff3333; /* medium pink-red*/
text-decoration:none;}

@charset "utf-8";
/* Green.CSS Color Schemes Document Chapter 11 Example 2 */
body{
color:#009933; /* dull medium green*/
background-color:#005826; /* dull dark green */}
/* theme links*/
a., a:link, a:hover, a:visited {}
a., a:link{color:#00ff00;} /* bright light neon green*/
a:hover{color: #33ff00;} /* bright green*/
a:visited{color:#00ff00;}
/* blog title styles*/
h1.blog-title, h1.blog-title a{
color:#99cc99; /* light pale green */
text-decoration:none;}
h2{
color:#33cc66; /* medium green */
text-decoration:none;}

h2 a {
color:#33cc66; /* medium green*/
text-decoration:none;}

h3.storytitle, h3.storytitle a{
color:#33cc66; /* medium green*/
text-decoration:none;}

Next, you have to create the options page that lets users make their choice and save it. Open your theme's directory and create a new directory inside it called admin. Inside the admin directory, create a file called options.php.

Open the options.php file, and insert the following code:

<?php
$settings = $this->get_settings();
$custom_schemes = $this->get_custom_themes();
?>
<div class="wrap">
<h2><?php _e('My Theme Options' ); ?></h2>
<?php if('1'==$_GET['updated']) { ?>
<div id="my-theme-options-updated" class="updated fade">
<p><?php _e( 'Settings saved!' ); ?></p></div>
<?php } ?>
<form method="post">
<table class="form-table">
<tbody>
<tr>
<th scope="row"><label for="custom-theme-header-color">
<?php _e('Custom Color Scheme'); ?></label></th>
<td>
<select name="custom-theme-color">
<option <?php selected( $settings[ 'color' ], '' ); ?>
value=""><?php _e('None'); ?></option>
<?php foreach( (array)$custom_schemes as $key =>
$name ) { ?>
<option <?php selected( $settings[ 'color' ], $key );
?> value="<?php echo esc_attr($key);
?>"><?php echo esc_html($name); ?></option>
<?php } ?>
</select>
</td>
</tr>
</tbody>
</table>
<p class="submit">
<?php wp_nonce_field( 'custom-theme-save-options' ); ?>
<input type="submit" class="button-primary" name="custom-theme-
save-options" id="custom-theme-save-options" value="<?php _e( 'Save'
); ?>" />
</p>
</form>
</div>

This file contains all of the code necessary for the theme options page. This particular options page contains a <select> drop-down menu that displays the available color schemes to the theme's user.

The next thing that you need to do is to hook the admin page into the WordPress administrative menu. Open or create your themes functions.php file, and insert the following code:

<?php 
if (!class_exists('My_Theme')) {
class My_Theme {

var $settings = null;

function My_Theme() {
add_action('admin_init', array(&$this, 'save_settings'));
add_action('admin_menu', array(&$this, 'add_admin_stuff'));
add_action('init', array(&$this, 'enqueue_color_css'));
}

function add_admin_stuff() {
add_theme_page(__('My Theme'), __('My Theme'),
'switch_themes', 'my-theme', array(&$this,

'display_theme_admin_page'));
}

function display_theme_admin_page() {
include (TEMPLATEPATH.'/admin/options.php');
}

function enqueue_color_css() {
$settings = $this->get_settings();
if( !empty( $settings['color'] ) && !is_admin() ) {
wp_enqueue_style( 'custom-theme-color',
get_bloginfo( 'stylesheet_directory' ) . '/schemes/' .
$settings[ 'color' ] );
}
}

function get_custom_themes() {
$schemes_dir = TEMPLATEPATH . '/schemes/';
$schemes = array();
if( is_dir($schemes_dir) && is_readable( $schemes_dir ) ) {
$dir = opendir($schemes_dir);
while(false !== ($file = readdir($dir))) {
if('.' != $file && '..' != $file) {
$scheme_name = ucwords(str_replace(
array('-','_','.css'), array(' ',' ',''), $file));
$schemes[$file] = $scheme_name;
}
}
}
return $schemes;
}

function save_settings() {
if (isset($_POST['custom-theme-save-options'])
&& check_admin_referer('custom-theme-save-options')
&& current_user_can('switch_themes')) {
$settings = $this->get_settings();
$settings['color'] = stripslashes(
$_POST['custom-theme-color']);
$this->set_settings($settings);
wp_redirect(admin_url('themes.php?page=my-theme&updated=1'));
}
}

function get_settings() {
if (null === $this->settings) {
$this->settings = get_option(
'My Theme Custom Settings', array());
}
return $this->settings;
}

function set_settings($settings) {
if (is_array($settings)) {
$this->settings = $settings;
update_option('My Theme Custom Settings', $this->settings);
}
}

}

$my_theme = new My_Theme();
}

This file hooks into two different WordPress administrative hooks. First, you add the administrative menu page by hooking to admin_menu. Then, you hook to admin_init to process and save the custom options present on the custom admin page. Finally, you hook to the init hook to enqueue the custom CSS stylesheet the user has selected.

After you save these files, go to your administrative menu and look at the sidebar on the left-hand side, under the Appearance heading. You should see a My Theme link, as shown in the following screenshot:

Advanced WordPress Themes

Now, click on the My Theme link under the Appearance menu heading. If you've done everything correctly, you should see an administrative page that looks like the one shown in the following screenshot:

Advanced WordPress Themes

Select a value, such as Red, from the drop-down selection menu, and then click on the Save button. You'll see the Settings saved! message, as well as the chosen color scheme selected in the Custom Color Scheme drop-down menu.

Finally, you can view the results of the color scheme change by opening up your site in a browser window. In the following screenshot, you can see what the page header of each of the three color schemes will look like:

Advanced WordPress Themes

WordPress 2.8 Themes Cookbook Over 100 simple but incredibly effective recipes for creating powerful, custom WordPress themes
Published: July 2010
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

(For more resources on Wordpress, see here.)

How it works...

You've done quite a few things in providing your theme's users with the ability to switch color schemes. First, you hooked a custom admin menu into the WordPress administrative interface, in order to provide a place for users to select their desired color scheme. You did this by taking advantage of the WordPress plugin API and the hooks admin_menu and admin_init.

You used the admin_menu hook to register your custom administrative page with a title of My Theme. After getting your administrative page to display, you allowed the user to save the values by using the admin_init hook to record the values in the WordPress database.

The most interesting part of the administrative menu that you created was the dynamic nature of the possible values in the <select> element. The get_custom_themes method opens the schemes directory located inside your theme. It then reads through all of the files in the schemes directory, sanitizes the filename, and provides these custom CSS files as options for the user to select. You can add or remove schemes in the future. Perhaps you want to give your users the option of using an ochre or monochrome color scheme. This is as easy as creating the files ochre.css and monochrome.css in your schemes directory. The system will automatically detect and offer these files as options to your theme's users.

The final WordPress hook that you took advantage of in this recipe is init. The init hook is fired after WordPress has initialized itself. Here, your hook callback checks to make sure that the user has chosen a color scheme and that a front-end page is being displayed. If both of these conditions are met, then the wp_enqueue_style function is used to enqueue the custom CSS file that your theme's user has chosen for their color scheme.

See also

Adding a theme options page

Changing the default Gravatar icon for your theme

A great way to build a community around a blog is to allow the users to personally identify themselves, either as authors or when commenting. Luckily, WordPress has built-in support for user avatars, by using the Gravatar service. Unfortunately, not all users have registered their e-mail address with Gravatar.com and they get stuck with a boring mystery man outline.

Luckily, WordPress allows administrators to change the default Gravatar for users who don't have them, and allows theme authors to provide custom defaults when their theme is active.

Getting started

You need to have created a WordPress theme containing at least a style.css file and an index.php file. Also, you should be using the get_avatar function somewhere within your theme. The wp_list_comments function uses the get_avatar function, so most themes satisfy this requirement.

How to do it...

First, you have to decide what your custom avatar for unknown users is going to be. The following smiley avatar will be used for the purposes of this recipe:

Advanced WordPress Themes

After you've selected the avatar that you'd like to use for unknown users, open your theme's directory and create a subdirectory named images. Inside the images directory, place the image file that you're going to use as your avatar, naming it something like avatar.jpg.

Next, open your administrative menu and go to Settings | Discussion. Scroll to the bottom of the page and look at the current list of possible default avatars. This should look like the example shown in the following screenshot:

Advanced WordPress Themes

Now, open or create your theme's functions.php file. Inside this file, insert the following code:

add_filter( 'avatar_defaults', 'add_my_theme_default_avatar' );

function add_my_theme_default_avatar($avatars) {
$avatars[get_bloginfo('stylesheet_directory') . '/images/avatar.
jpg'] = __( 'My Theme Avatar' );
return $avatars;
}

Save the functions.php file and reload the Settings | Discussion page. You should see something similar to the following screenshot:

Advanced WordPress Themes

The previous screenshot shows that your custom avatar has been added to the avatar options.

Select your theme avatar and save the discussion options. Then, when an unknown user has their avatar displayed on the frontend of the site, it will look something like the following screenshot:

Advanced WordPress Themes

How it works...

Providing a custom avatar is a simple matter of hooking to the correct filter and returning the correct values. Here, you hook to the avatar_defaults filter. Your callback function receives an array of avatars that WordPress and other plugins provide. You add an array item by using your image location as the key and your avatar description string My Theme Avatar as the array value.

In this instance, the key is a URL to an image located in the theme's images directory, and the description is the string My Theme Avatar. Of course, after you provide the default avatar, the theme's user still has to select it for it to become active.

There's more...

Sometimes, either for design purposes or as part of other project requirements, you may want to have more control over when and how your avatar is used.

Forcing your theme to use your default avatar

Although it is great to give the user a choice, sometimes you just want to make sure that the theme uses your custom default avatar. This is appropriate in cases where your end user doesn't have a lot of technical expertise, or you are setting up a site for someone and don't want to let them change the default avatar while your theme is active.

Open or create a functions.php file, and insert the following code:

add_filter('avatar_defaults', 'add_my_theme_default_avatar');
add_filter('pre_option_avatar_default', 'force_my_theme_default_avatar');
function add_my_theme_default_avatar($avatars) {
return array();
}
function force_my_theme_default_avatar($value) {
return get_bloginfo('stylesheet_directory') . '/images/avatar.jpg';
}

Save and upload the functions.php file to your server.

Within the functions.php file, you're doing a few things. First, with the preceding code, you remove all the options from the default avatar options selection on the Settings | Discussion menu.

This results in the screen displaying no avatar choices to the user as shown in the following screenshot:

Advanced WordPress Themes

Next, you're overriding the get_option return value when the option being fetched is default_avatar. In this case, you're overriding the return value by providing the URL to your own custom avatar.

Summary

In this article, we saw how to take our theme to the next level, by adding theme options, allowing for multiple theme color schemes and by changing the default Gravatar icon for the theme


Further resources on this subject:


WordPress 2.8 Themes Cookbook Over 100 simple but incredibly effective recipes for creating powerful, custom WordPress themes
Published: July 2010
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Lee Jordan

Lee Jordan is a web developer with a large collection of web technology acronyms on her resume that sound like the names of laundry detergents and cause glazed expressions in school children. She designs and maintains internal and external enterprise-level websites and web-based applications as part of a project team for a privately held technical services company. Her work includes proposing, writing, and editing web content and user guides people actually read. She began her career in 1997 as a web designer after graduating from Florida State University with a Bachelor of Fine Arts, where she swears that she missed at least one home football game while in the computer lab. Lee later convinced Seminole Community College to give her a Web Programming degree in 2003, even though her final project was a Java-based application that actually contained a usable help file. Web development topics or whatever she can think of at the time are posted on her blog at http://leejordan.net.

Nick Ohrn

Nick Ohrn has been creating with WordPress for more than five years and has worked with some of the biggest media companies in the USA.  In his day to day work, he deals with the WordPress source, creates custom themes and plugins, and helps his clients and customers utilize WordPress to run their sites and their businesses.  Nick has a Bachelor’s of Science in Computer Science from the Rose-Hulman Institute of Technology and works full time as a web developer with an emphasis in WordPress development.  He resides in Seattle, WA and works with people and companies from around the world.

Books From Packt

Joomla! 1.5 Site Blueprints
Joomla! 1.5 Site Blueprints

Plone 3 Multimedia
Plone 3 Multimedia

JSF 2.0 Cookbook
JSF 2.0 Cookbook

Liferay Portal 6 Enterprise Intranets
FreeSWITCH 1.0.6

Oracle Application Express 3.2 – The Essentials and   More
Oracle Application Express 3.2 – The Essentials and More

Liferay Portal 6   Enterprise Intranets
Liferay Portal 6 Enterprise Intranets

WordPress 2.9 E-Commerce
WordPress 2.9 E-Commerce

WordPress 3 Site Blueprints
WordPress 3 Site Blueprints

No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
a
t
c
Q
q
b
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software