Creating Theme Options


Written by Sarah from Stuff By Sarah

If you create WordPress themes then a useful addition to a standard theme is to give the user a simple way to change the logo or header in use, perhaps allow them to change the colour of the background, the width of the site too. These options are designed to save people time but more importantly, to make it easy for non-developers to make a few alterations to their theme without needing to go looking through the code.

So first we need to create an admin page to go into the Appearance menu. To do this we can insert the page into the theme’s functions.php file. We create the page similar to how we created admin pages for our plugin. e.g.

add_action('admin_menu', 'ourtheme_add_theme_pg');

function ourtheme_add_theme_pg() {
    add_theme_page(__('Theme Options'), __('Theme Options'), 'edit_themes', basename(__FILE__), 'ourtheme_functions');
}

This will add a new menu item called Theme Options into our Appearance menu in the admin. Then we need to decide what options we’re going to offer the users. Bear in mind, the more options you offer, the more code is required and the slower the site can become. I’ve seen a site slow down from 0.5 seconds to 15 seconds load time, just due to a badly written theme options page!

So let’s allow the user to change the image file used. In the theme directory you can create an images directory to store a number of different banners (or the user can add more of their own), so we’ll just give them the option of choosing one of these rather than going through the code of how to upload an image to the website.

The Basic Admin Page

Let’s just grab the basic admin page code again to use as our template:

<div class="wrap">
 	<form id="options_form" method="post" action="">
		<h2>< ?php _e('Theme Options'); ?></h2> 

		<div class="ui-sortable">
			<div class="postbox">
				<h3 class="hndle">< ?php _e('Sub Header'); ?></h3>
				<div class="inside">

					** Form or content goes here **

				</div>
			</div>
		</div>
	</form>
</div>

List Banners Available

On the page we’ll check all of the banners available within the images directory and list them in a select list. We’ll also pre-select the current one used:

<div><label for="topimg">Top Banner</label>
<select id="topimg" name="topimg">
< ?php
$template_dir = get_template_directory();
$default_file = "header.gif";
$allowed_file_ext = array(".gif", ".png", ".jpg", "jpeg");

if (get_option("ourtheme_header")) $default_file = get_option("ourtheme_header");

if ($handle = opendir($template_dir.'/images/')) {
    while (false !== ($file = readdir($handle))) {
        if (in_array(substr($file, -4), $allowed_file_ext) {
            echo "<option value='".$file."'".($file == $default_file ? ' selected="selected"' : '').">".$file."\n";
        }
    }
    closedir($handle);
}
?>
</select></div>

Here we open up the images directory within the template directory (found by using the WordPress function get_template_directory()) and then loop through each file found and add it to our select list providing it is an image file (achieved by checking the last 4 characters of each file found against the array of file extensions). This also checks the filename against the current file in use and marks the option as selected if it matches.

This code, along with a submit button is then inserted into our default admin page code above.

Process the Form

To process the form all we need to do is check the submit button has been clicked, if it has then grab the image selected and store it in our options table i.e.

if (isset($_POST['theme_submit'])) :
    update_option('ourtheme_header', $_POST['topimg']);
    echo '<div id="message" class="updated fade"><p><strong>'.__('Options saved.').'</strong></p></div>';
endif;

Final Admin Code

This gives us the final code to go into our functions file of:

add_action('admin_menu', 'ourtheme_add_theme_pg');

function ourtheme_add_theme_pg() {
    add_theme_page(__('Theme Options'), __('Theme Options'), 'edit_themes', basename(__FILE__), 'ourtheme_functions');
}

function ourtheme_functions() {
    if (isset($_POST['theme_submit'])) :
        update_option('ourtheme_header', $_POST['topimg']);
        echo '<div id="message" class="updated fade"><p><strong>'.__('Options saved.').'</strong></p></div>';
    endif;
?>

<div class="wrap">
 	<form id="options_form" method="post" action="">
		<h2>< ?php _e('Theme Options'); ?></h2> 

		<div class="ui-sortable">
			<div class="postbox">
				<h3 class="hndle">< ?php _e('Sub Header'); ?></h3>
				<div class="inside">

					<div><label for="topimg">Top Banner</label> <select id="topimg" name="topimg">
						< ?php
						$template_dir = get_template_directory();
						$default_file = "header.gif";
						$allowed_file_ext = array(".gif", ".png", ".jpg", "jpeg");

						if (get_option("ourtheme_header")) $default_file = get_option("ourtheme_header");

						if ($handle = opendir($template_dir.'/images/')) {
						    while (false !== ($file = readdir($handle))) {
						        if (in_array(substr($file, -4), $allowed_file_ext) {
						            echo "<option value='".$file."'".($file == $default_file ? ' selected="selected"' : '').">".$file."\n";
						        }
						    }
						    closedir($handle);
						}
						?>
					</select></div>

				</div>
			</div>
		</div>
	</form>
</div>

< ?php } ?>

Front End Edits

Finally all we need to do is set up the code for the header.php file to check which banner to display. So wherever the banner is displayed we just need to take the default image filename out and use the following PHP code:

<img src="< ?php bloginfo('template_url');
$headerimg = "header.gif";
if (get_option("ourtheme_header")) $headerimg = get_option("ourtheme_header");

echo "/images/".$headerimg." />" alt="Top Banner" />

Alternatively, if your banner is using the image replacement technique, then you’re best off adding an action to add the CSS style needed to the wp_head() function in your function.php theme file e.g.

add_action("wp_head", "ourtheme_addheader");

function ourtheme_addheader() {
    if (get_option("ourtheme_header")) :
        echo '<style type="text/css">#header { background: url('.get_option("ourtheme_header").'); </style>';
    endif;
}

This will then insert the style to override the default styling set up in your CSS stylesheet.

This is just a simple example of creating an options page for your theme, but the logic is the same for virtually all the options you could want to offer. Just create the various form elements to allow the user to make their changes, and save the selections and information in the options table using unique option names.


Copyright © 2009 Blogging Tips. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact us so we can take legal action immediately.

Written by Sarah from

No Comments

Comments are closed.