WordPress Theme Design with Options Administration

written by aext on October 1, 2009 in Popular and WordPress with 76 comments

Are you running WordPress? And how are you controlling all options of your current wordpress theme? WordPress offers you get_option() function to get the options of your wordpress. However, all of default options wordpress gives to you are not enough. You maybe want to add more options that easy to implement on your theme design. How to do that? This tutorial will help you create options and administrate them in wordpress admin page.

Theme Options


All of wordpress options are stored in the database under table wp_options, and your theme options will be so. Let’s see the structure of wp_options table, all the field, and data type of each are:

  • option_id – BIGINT
  • blog_id – INTEGER
  • option_name – VARCHAR
  • option_value – LONGTEXT
  • autoload – VARCHAR

All you need are the fields in bold, because you use the function get_option() to get options with the name in option_name filed, and the option_value, of course is what you need to get.
The default using of get_option() is:

<?php echo get_option( $show ); ?>

And the code above is the same as the query below:

get_option() funtion and return value

However, you should know the difference is the function will return FASLE if the desired option does not exist, or no value is associated with it, but the query will return null.

How do we process an option?


At first, you have to declare an option on your theme functions.php file. The simple option is fine for configuration and getting will be declared as:

// theme options $options = array(

  array(
    "name"      => "Option Title",
    "desc"      => "Option Description",
    "id"        => "Option Unique ID", //This is option_name filed in the database     "default"   => "10"), //Its default value 
);

Your theme setting page will as good as display as image below:

get_option - The option display on setting page

Hey, but before getting a result above, we have to write some code for displaying. As an example, I will make a block of an option. In my case, I want to set an option for number of Community News article will be displayed on the homepage.

Declare the option:

<?php

$options = array(

  array(    
    "name" => "<strong>Homepage Community Entries</strong>",
    "desc" => "Select the number of Community entries that should appear on the Index page",
    "id" => "aext_numcomnews",
    "default" => "10"),

);

?>

The code to display:

 <div class="stuffbox">
  <h3>Homepage Setting</h3>
  <div class="inside">
    <table class="form-table"style="width: auto">
    <?php
     foreach($options as $value) {
      switch( $value['id'] ) {
        case "aext_numcomnews": ?>
        <tr>
        <th scope="row"><?php echo $value['name']; ?><br /><?php echo $value['desc']; ?></th>
        <td>
         <input name="<?php echo $value['id']; ?>"                 id="<?php echo $value['id']; ?>"type="text"                 value="<?php get_option($value['id'])?printf(get_option($value['id'])): printf($value['default']) ?>" />
        </td>
        </tr>

      <?php break;
        }
    }
    ?>
   </table>
  </div>
 </div>

And, here is the result …

get_option - display in theme setting page

Where’s the Theme Setting Page?


We already write a lot of code for theme setting page, but we can not edit/update the option without display page. Let’s see how to add a link which link to theme setting page.
At first, you have to understand what your functions.php looks like. To make it easy, the name and the content of this functions.php are:

<?php

$options = array(

  //All your options will be declared here    
);

//This function is used for processing function themename_options() {
  global $options;

    add_theme_page('Theme Setting', 'Theme Setting', 10, 'themename-settings', 'themename_admin');
}

//All the code of displaying will be here function themename_admin() {
    global $options;

}

add_action('admin_menu', 'themename_options');

?>

The add_theme_page() function is used to add a page to a add a page to your WP admin. Here it is, this page is your theme setting page. The third parameter is included as unique URL to this page. Example with this URL below is the link to a theme setting page:

http://localhost/wp-admin/themes.php?page=themename-settings

The add_action() function is used to hook function themename_option() and create a menu item in admin menu. You cannot access your theme setting page without this function.

You know what? The menu item that link to this page can be added with two different type. The add_theme_page() above will add an item into Theme Menu. You can use this code below to add a separated menu item as another parent menu item.

Replace the add_theme_page() by add_menu_page() with the same parameters:

    add_menu_page('Theme Setting', 'Theme Setting', 10, 'themename-settings', 'themename_admin');

Take a look:

Menu Item Style for Theme Setting Page

Complete the setting page code


You need more works to make your setting page run smooth. Now, we will combine all the code together. First code block that we start completing code is option array:

// theme options $options = array(

  array(    
    "name" => "<strong>Homepage Community Entries</strong>",
    "desc" => "Select the number of Community entries that should appear on the Index page",
    "id" => "aext_numcomnews",
    "default" => "10"),

  array(
   "id" => "aext_footer",
   "default" => ""),

);

In this tutorial, I just use two options to make it easy to look. We have two options above, right? But we just need to focus on the value of id of each array, because the code below will get value of id and we can identify what option we update by unique id.

<?php

.....

function themename_admin() {
    global $options;
?>
<div class="wrap">
  <h2 class="alignleft">Theme Setting</h2>
  <br clear="all" />

  <?php
    //Check if settings saved!     if( $_REQUEST['saved'] ) {
  ?>
        <div class="updated fade"><p><strong>Setting Saved</strong></p></div>
  <?php } ?>

<form method="post"id="myForm">
<div id="poststuff"class="metabox-holder">

 <div class="stuffbox">
  <h3>Homepage Setting</h3>
  <div class="inside">
    <table class="form-table"style="width: auto">
    <?php
     foreach($options as $value) {
      switch( $value['id'] ) {
        case "aext_numcomnews": ?>
        <tr>
        <th scope="row"><?php echo $value['name']; ?><br /><?php echo $value['desc']; ?></th>
        <td>
         <input name="<?php echo $value['id']; ?>"                 id="<?php echo $value['id']; ?>"type="text"                 value="<?php get_option($value['id'])?printf(get_option($value['id'])): printf($value['default']) ?>" />
        </td>
        </tr>

      <?php break;
        case "aext_footer": ?>
        <tr>
          <th scope="row">
            <strong>Footer HTML</strong>
            <br />Put some HTML code here. That's helpful if you want to add tracking code ....
          </th>
          <td>
            <textarea class="code"rows="4"cols="60"                         name="<?php echo $value['id']; ?>"                         id="<?php echo $value['id']; ?>"><?php print get_option($value['id']); ?>
            </textarea>
          </td>
        </tr>

      <?php break;
        }
    }
    ?>
   </table>
  </div>
 </div>  

</div>
<input name="theme_save"type="submit"class="button-primary"value="Save changes" />
<input type="hidden"name="action"value="theme_save" />
</form>

</div>
<?php
}

.....

?>

At the top of this block of code above, we check the value of the request saved. The text will displays to notify that setting was saved successful. The form will load default value of id: aext_numcomnews if there are no value of aext_numcomnews in database.

That is the form display. We need to process the value that the form submitted. We do it inside themename_options() function:

<?php

function themename_options() {
  global $options;

  if('theme_save'== $_REQUEST['action'] ) {

    foreach($options as $value) {
     if( !isset( $_REQUEST[ $value['id'] ] ) ) {  
        //Do nothing      } else {
        update_option( $value['id'], stripslashes($_REQUEST[ $value['id']])); }
     }

     if(stristr($_SERVER['REQUEST_URI'],'&saved=true')) {
        $location = $_SERVER['REQUEST_URI'];
     } else {
        $location = $_SERVER['REQUEST_URI'] . "&saved=true";
     }

     header("Location: $location");
     die;
  }

  add_theme_page('AEXT Theme Setting', 'AEXT Theme Setting', 10, 'aext-settings', 'aext_admin');
}

?>

That function processes the data submitted by update_option() with parameter is the value of each id was changed. After submit your changes, your all changes will be made in table wp_options in your database.

At last, remember to put the line of code here at the end of your functions.php file:

add_action('admin_menu', 'themename_options');

If you want to rest your current options to default value, simply copy and paste these code next to your current form. The reason is we can not submit two value theme_save and theme_reset at same time.

<form method="post">
    <p class="submit"style="border: 0;">
       <input name="reset"type="submit"value="Reset" />
       <input type="hidden"name="action"value="theme_reset" />
    </p>
</form>

And edit your theme_options() funtion like this:

  if('theme_save'== $_REQUEST['action'] ) {

    .....

  } else if('theme_reset' == $_REQUEST['action'] ) {

    foreach($options as $value) {
     delete_option( $value['id'] );
     $location = $_SERVER['REQUEST_URI'] . "&reset=true";
    }

    header("Location: $location");
    die;

  }

Get your options in your theme files


It’s as easy as the code at the top of this entry. Because all of your options are stored in database, we will get values for a named option from the options database table. If the desired option does not exist, return value is FASLE.

In my index.php file:

......

<?php

    $numcomnews = get_option('aext_numcomnews');

    query_posts("category_name=Community News&showposts=$numcomnews");

    if(have_posts()) :

    //Displaying posts     
    endif;

?>

......

What’s up?


The completed code is attached in this post, you can download it for use later. However, I suggest that you follow step by step to help you get all what I want to say. This tutorial comes along with only two options, you can add more options to customize your own wordpress template. Although these code is working, maybe I am doing something wrong. Feel free to comment, I’ll really appreciate all you give to me!