<

Custom Theme Options in WordPress

So you want to add a new layer of customization to your WP theme in order to appeal to more customers or just to make modifications to your theme easier with a front-end system? Well, now you’ll know how to easily set one of these up inside your theme and take your theme to a new level of usability and usefullness.

Step 0: The Principle Behind It All

If it helps you to understand everything we’re going to be doing in a few seconds, you can think of our “Theme Opitons” component of the theme as a plugin that gets activated along with the theme, and since WordPress is gonna use this mindset as well, we’ll have access to a majority of the same functions that plugins do.

Step 1: Creating the Menu

First things first, in order to create our interface to change our options, we need a place to put that interface. “Where?” Should be your next question, and the answer is “In the ‘Appearance’ tab of the WP-Admin.” We’re going to be creating a submenu under the appearance tab that will hold all of our customizaitons interface.

To make the submenu appear, we need to call the function add_action() and give it the parameters “admin_menu”,”BWPT_theme_options” in that order. Once we do that, we need to write the function “BWPT_theme_options” and fill it with the function add_theme_page() and give it the parameters: ‘Manage Theme Options’, ‘Theme Options’, ‘edit_themes’, ‘BWPT_theme_options’, ‘BWPT_theme_options_admin’.

// Custom theme options
add_action('admin_menu', 'BWPT_theme_options');
 
function BWPT_theme_options() {
    add_theme_page('Manage Theme Options', 'Theme Options', 'edit_themes', 'BWPT_theme_options', 'BWPT_theme_options_admin');
}

Step 2: Creating the defaults

Before we go any further, lets create the default values for our customizations. For the tutorial, we’re going to be adding 2 options: custom background color and a custom CSS area.

Let’s begin by making a new function, BWPT_theme_options_admin (this is also the function we referenced in the last parameter of add_theme_page and will be the function that displays the HTML of the customization page). First thing inside of this function is gonna be an if-statement to check to see if the page viewer has rights to edit the theme (Administraitor only) and if they can’t, then kill the page load so they can’t edit any theme settings.

function BWPT_theme_options_admin() {
 
    if (!current_user_can('edit_themes'))  {
        wp_die( __('You do not have sufficient permissions to access this page.') );
    }
 
}

Next, we’re going to create a variable called $BWPT and have it’s value be the function get_option() with the parameter “BWPT_theme_options”. Get_option will grab the corresponding data from the wp_options table in the database that we supply it in the parameter, if it doesn’t find a match, then it will return false. So we’ll use this to check to see if the customizations have already been made, and if not, then add the defaults to the database.

Adding options to the database is easy using the function add_option(). You just supply it with a key (a name) and a value. To save time, space, memory, and add convienence, you should always have your options inside of an array and then add the array to the options table, so you have 1 row to get and 1 row to update.

$BWPT = get_option('BWPT_theme_options');
 
if(!$BWPT){
    $BWPT_defaults = array();
    $BWPT_defaults['background-color'] = '#cccccc';
    $BWPT_defaults['other-css'] = '';
 
    add_option( "BWPT_theme_options", $BWPT_defaults );
}

Step 3: Adding the HTML

Now that we have a page and some options, we can put in some HTML to start editing them. Basically our entire page is going to consist of a form (formatted via tables) and each input we’re going to output the options we set up last step (remember, they’ll already be at the defaults if they’re not changed so we don’t have to bother with any if/else statements). This step is really simple and requires no explination, just be sure to notice how the tables are set up and the classes applied to each element (using classes from the admin CSS will help give your options page more uniformity with the rest of the back-end).

$BWPT_admin_html = "
 
<div class="wrap">
 
<h2>Manage Theme Options</h2>
 
 
        {$updated_html}
<form id="BWPT-form" method="post">
 
<table class="form-table">
<tbody>
<tr>
<th valign="top" scope="row"><label for="background-color">Background Color: </label></th>
<td>
<input id="background-color" class="regular-text" maxlength="7" name="background-color" type="text" value="{$BWPT[&quot;background-color&quot;]}" /></td>
</tr>
<tr>
<th valign="top" scope="row"><label for="other-css">Other CSS</label></th>
<td><textarea id="other-css" style="width: 90%;" cols="45" rows="10" name="other-css">{$BWPT["other-css"]}</textarea></td>
</tr>
</tbody>
</table>
 
 
<span class="submit" style="border: 0;">
<input name="submit" type="submit" value="Save Settings" /></span>
        </form></div>
 
 
";
echo $BWPT_admin_html;

Step 4: Updating the Options

We have our form setup, so let’s use it to save the changes to our theme options. You’ll notice that our form tag has an empty action attribute, that’s so the page will reload when we press submit and we don’t have to make another file to handle the update methods. To start, inside of that same admin function we’re going to add a new if-statement that checks the $_POST globals for the submit button id (‘submit’), and if it is set, then we’re going to use the function update_option to update the database info (after we make it safe with the function mysql_real_escape_string()) and we’re also going to make a new variable, $update_html, and fill it with some html to let the user know that the update went through.

if(isset($_POST['submit'])){
    $BWPT['background-color'] = mysql_real_escape_string($_POST['background-color']);
    $BWPT['other-css'] = mysql_real_escape_string($_POST['other-css']);
    update_option('BWPT_theme_options',$BWPT);
 
    $url = get_bloginfo('url');
    $updated_html = "
 
<div id="message" class="updated below-h2">
 
Header updated. <a href="{$url}">Visit your site</a> to see how it looks.</div>
 
 
    ";
}

Step 5: Using these options

Now that we have the options in the database, we can use them in our themes by calling get_option. In our example, we created a custom background color, and specificed some other css to include as well. There are 2 ways we could add these changes to our theme: write it into the header.php file or use the action “wp_head”. We’ll cover both ways.

Let’s start with the action method, we’re going to create a new function (outside the admin function) called BWPT_theme_options_client and inside the function use get_option to get the changes from the database and then we’ll echo out the css inside some style tags. In order for this to work though we need to call the add_action() function with the parameters: ‘wp_head’, ‘BWPT_theme_options_client’. This will add our new CSS where the function wp_head() is called in our theme.

if(get_option('BWPT_theme_options')){
    function BWPT_theme_options_client(){
        $BWPT = get_option('BWPT_theme_options');
 
        $BWPT_styles = "
<!--
                body {background-color: {$BWPT["background-color"]};}
                {$BWPT["other-css"]}
 
-->
 
        ";
        echo $BWPT_styles;
    }
    add_action( 'wp_head', 'BWPT_theme_options_client' );
}

The second method involves removing the function we made and pasting it’s contents wherever we want the changes to be applied (in our case, header.php).

if(get_option('BWPT_theme_options')){
    $BWPT = get_option('BWPT_theme_options');
 
    $BWPT_styles = "
<!--
            body {background-color: {$BWPT["background-color"]};}
            {$BWPT["other-css"]}
 
-->
 
    ";
    echo $BWPT_styles;
}
 
<h2>the final changes</h2>

Finished!

That’s all there is to theme options folks! Some improvements you can make to what we built today are checks to see if a field was left blank and if it was, change it back to it’s default value. If you have any questions or concerns about the tutorial, please leave a comment!

Final Code With Comments

function BWPT_theme_options_admin() { // Handles everything inside the WP-Admin
 
    if (!current_user_can('edit_themes'))  { // If the user isn't an administraitor or one with the ability to make changes to the theme
        wp_die( __('You do not have sufficient permissions to access this page.') ); // stop the rest of the page from loading
    }
 
    $BWPT = get_option('BWPT_theme_options'); // get the customizations from the database
 
    if(!$BWPT){ // if the customizations don't exist yet
        $BWPT_defaults = array(); // create an empty array
        $BWPT_defaults['background-color'] = '#cccccc'; // set the default background color
        $BWPT_defaults['other-css'] = ''; // set the default custom css
 
        add_option( "BWPT_theme_options", $BWPT_defaults ); // add our customizations to the database
    }
 
    if(isset($_POST['submit'])){ // If they've clicked the submit button
        $BWPT['background-color'] = mysql_real_escape_string($_POST['background-color']); // escape and save the new background color
        $BWPT['other-css'] = mysql_real_escape_string($_POST['other-css']); // escape and save the new custom css
        update_option('BWPT_theme_options',$BWPT); // update the database
 
        $url = get_bloginfo('url'); // get the blog url from the database
        $updated_html = "
 
<div id="message" class="updated below-h2">
 
Header updated. <a href="{$url}">Visit your site</a> to see how it looks.</div>
 
 
        "; // some HTML to show that the options were updated
    }
 
    $BWPT_admin_html = "
 
<div class="wrap">
 
<h2>Manage Theme Options</h2>
 
 
            {$updated_html}
<form id="BWPT-form" method="post">
 
<table class="form-table">
<tbody>
<tr>
<th valign="top" scope="row"><label for="background-color">Background Color: </label></th>
<td>
<input id="background-color" class="regular-text" maxlength="7" name="background-color" type="text" value="{$BWPT[&quot;background-color&quot;]}" /></td>
</tr>
<tr>
<th valign="top" scope="row"><label for="other-css">Other CSS</label></th>
<td><textarea id="other-css" style="width: 90%;" cols="45" rows="10" name="other-css">{$BWPT["other-css"]}</textarea></td>
</tr>
</tbody>
</table>
 
 
<span class="submit" style="border: 0;">
<input name="submit" type="submit" value="Save Settings" /></span>
            </form></div>
 
 
    "; // all the admin area HTML
    echo $BWPT_admin_html; // display the admin area HTML
}
 
if(get_option('BWPT_theme_options')){ // if the customizations exist
    function BWPT_theme_options_client(){ // display function for the customizations
        $BWPT = get_option('BWPT_theme_options'); // get our customizations from the database
 
        $BWPT_styles = "
<!--
                body {background-color: {$BWPT["background-color"]};}
                {$BWPT["other-css"]}
 
-->
 
        "; // put our customizations into some style tags
        echo $BWPT_styles; // display the style tags
    }
    add_action( 'wp_head', 'BWPT_theme_options_client' ); // attach our display function to the wp_head function
}
Bookmark and Share

Comments are closed.