Recent Tweets

 
How To Add A WordPress Theme Options Page

How To Add A WordPress Theme Options Page

Last Updated: August 21, 2009 7:00 pm 3 comments

In this post you’ll find out how to add and create a custom wordpress theme options page inside the administration area which will let you Add/Edit your own Youtube video, for use in your sidebar.

What will be created

wp-admin-theme-settings

Download the Source Code

Download Now

Getting Started

In order for you to add your theme settings page you will have to modify a few files located inside you wordpress theme directory this is normally located in:

/wp-content/themes/YourThemeName/

As long as you have proper write permissions on your theme folder You can use the built in wordpress theme editor to edit all the theme files for creating your theme options page, If not i would recommend using the FREE fireftp plugin for firefox, to download/edit the files locally.

The first file we need to edit will be the functions.php file, this file loads first before the theme is processed, which acts in the same manner as a plugin: read more on the functions.php file.

Functions.php

you can just paste the code from our options page straight into the functions.php file, but I like to keep it clean so we can reference our options page inside the functions.php file first.

<?php include("options.php");?>

We can then create a new page inside your themes root directory(if you can), called “options.php” Where first part of the code can be pasted in.

Options.php

$settings = array(
 'youtube' => 'kGl-2Lst1Kk' //Greenock Donnies Quad Biking Video
);
$themename = "Your Theme Name";
$shortname = "yourthemename";
$options = array (
              array(  "name" => "Main Options",
                      "type" => "header"
              ),
              array(  "name" => "Youtube Video ID",
                      "id" => $shortname."_youtube",
                      "std" => $settings['youtube'],
                      "type" => "text",
                      "note" => "<strong>Example: </strong> http://www.youtube.com/watch?v=<strong style='color: #ff0000;'>kGl-2Lst1Kk</strong>"
              )
 );
?>

The above starts to build a few array’s to hold our settings in place were we can reference them using very simple calls,

Settings

The main settings holds one default variable called “$settings” this will Initialize our Associative Array this holds 2 values, the main option called Name with a value of “youtube“, and the type with a value of “header

We don’t want the script to load and break the front end of the website, when there’s no default data to pull the video from youtube(Ok so it might not break it, but will, at least generate a few javascript errors, so we put in place a default value.)

Options

The options array builds out our mini plugin which we can manipulate using the associative arrays, setting the theme name along with short names allows us to access a variable to call when needed.

function mytheme_add_admin() {
         global $themename, $shortname, $options;
             if ( $_GET['page'] == basename(__FILE__) )
             {
                  if ( 'save' == $_REQUEST['action'] )
                  {
                      foreach ($options as $value)
                      {
                             if ($value['type']!='header')
                         {
                             update_option( $value['id'], $_REQUEST[ $value['id'] ] );
                         }
                      }
                      foreach ($options as $value)
                      {
                             if( isset( $_REQUEST[ $value['id'] ] ) )
                             {
                                 update_option( $value['id'], $_REQUEST[ $value['id'] ]  );
                             } else {
                                 delete_option( $value['id'] );
                             }
                      }
                      header("Location: themes.php?page=settings.php&saved=true");
                      die;
                  } else if( 'reset' == $_REQUEST['action'] )
                      {
                          foreach ($options as $value)
                      {
                          delete_option( $value['id'] );
                      }
                          header("Location: themes.php?page=settings.php&reset=true");
                          die;
                      }
                   }
add_theme_page($themename." Options", "Theme Options", 'edit_themes', basename(__FILE__), 'mytheme_admin');
}// end function

function mytheme_admin() {
         global $themename, $shortname, $options;

         if ( $_REQUEST['saved'] ) echo '<div id="message"><p><strong>'.$themename.' settings saved.</strong></p></div>';
         if ( $_REQUEST['reset'] ) echo '<div id="message"><p><strong>'.$themename.' settings reset.</strong></p></div>';

// leave the function "<em>mytheme_admin()</em>" Open until for part 2 of the code.
?>

The main function at the top “mytheme_add_admin()” will check the $_GET;  then do a series of checks to identify any requests that may be passed, either through the $_GET or $_POST method which will be referenced through the $_REQUEST variable which contains the content of both $_GET, $_COOKIE, and $_POST.

The First check: will see if our form was posted, which includes our “action” with a value “save“, then loop through our options and using the wordpress hook “update_option()” which will update our options in the database, then  finally redirecting the user back to the themes page, with a nice fade-in message.

The Second check: Still checks to see if the form was posted, but this time, checks to see if “action” has a value of “reset“, if this is present then the user must have clicked the reset button, this will use the wordpress hook “delete_option()” and remove the options set in the database for our video id.

The End: of the Function also uses a wordpress hook “add_theme_page()“,

This builds out our Options page in the administration area, the first parameter of the function takes our “$themename” variable and appends “settings” to the end of it to produce: “Your theme name Options” which will be the title header used on the options page,

The next parameter is the “Name, which is used inside the navigation sidebar, the “edit_themes” parameter tells wordpress to insert the “Theme Options” text inside the Appearance navigation block on the sidebar, So when you click expand on the Appearance tab it will show.

wp-theme-options

Theme Options Visible in Under the Appearence tab.

Admin Page

In order for us to have our admin options page, we will need to build our options page, this will load after clicking the Theme options link, the first thing were going to do introduce some CSS styles to the page,

<style type="text/css">
th { text-align: left; }
td { padding: 5px 10px !important; }
tr.header {background-color: #99CC66 !important;color: #ffffff;}
.header td {padding: 2px 10px !important;font-size: 14px !important;font-weight: bold !important; }
</style>

The Wrap

The Wrap is what we are given to use as a container to bring the wordpress theme options inline with the current default admin css within the admin area, The class which when used, can encompass a lot of various already defined wordpress styles.

The Area in which you can modify

The Area in which you can modify

<div class="wrap">
 <h2><?php echo $themename; ?> Settings</h2>
  <form method="post">
    <table class="form-table">
<?php foreach ($options as $value) { if ($value['type'] == "text") { ?>
<tr>
    	   <th scope="row" style="width: 25%">
<?php echo $value['name']; ?>:
</th>
       	   <td>
        	<input onfocus="this.select();" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" value="<?php if ( get_settings( $value['id'] ) != "") { echo get_settings( $value['id'] ); } else { echo $value['std']; } ?>" />
&nbsp; &nbsp; <?php echo $value['note']; ?>
    	   </td>
</tr>
<?php } elseif ($value['type'] == "select") { ?>
    	<tr>
        <th scope="row">
              <?php echo $value['name']; ?>:
        </th>
          <td>
            <select name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>">
                <?php foreach ($value['options'] as $option) { ?>
                <option value="<?php echo $option; ?>" <?php if ( get_settings( $value['id'] ) == $option) { echo ' selected="selected"'; } elseif ($option == $value['std']) { echo ' selected="selected"'; } ?>>
                   <?php echo $option; ?>
                </option>
                <?php } ?>
            </select>
&nbsp; &nbsp; <?php echo $value['note']; ?>
        </td>
    </tr>
<?php } elseif ($value['type'] == "header") {?>
<tr class="header">
          <td colspan="2">
             <?php  echo $value['name'] ?> &nbsp; &nbsp;
                <span style="font-size: 11px; font-weight: normal;">
                  <?php echo $value['note']; ?>
                </span>
           </td>
         </tr>
<?php  }  } ?>
     </table>
     <p class="submit">
     <input name="save" type="submit" value="Save changes" />
     <input type="hidden" name="action" value="save" />
    </p>
  </form>

  <form method="post">
   <p class="submit" style="border: 0;">
    <input name="reset" type="submit" value="Reset" />
    <input type="hidden" name="action" value="reset" />
   </p>
  </form>
</div>
<?php }//end function `mytheme_admin()` ?>
<?php
function mytheme_settings($key) {
global $settings;
return $settings[$key];
}?>

The Wrap Exposed

This is what will be created once the codes been uploaded.

wp-admin-theme-settings

CSS Admin Styles

Included within the class wrap is a variety of various other classes that you can use inside your Theme Options page, these are outlined below, these give various design astetics to either the theme options page or if your creating a wordpress plugin these will give it a more wordpress look and feel without the hassle of creating your own styles.

The Various CSS styles which can be applied

The Various CSS styles which can be applied

CSS Admin Styles

The last thing that to be added to the “settings.php” page will be our wordpress hook to add the “mytheme_add_admin” to our admin menu, with a small for loop to grab and loop through our options for the theme settings.

<?php add_action('admin_menu', 'mytheme_add_admin'); ?>
<?php
   foreach ($options as $value) {
       if (get_settings( $value['id'] ) === FALSE)
       {
           $$value['id'] = $value['std'];
       } else {
           $$value['id'] = get_settings( $value['id'] );
       }
   }

   foreach ($settings as $k=>$v) {
      $var = $shortname.'_'.$k;
      if (!empty($$var)) $settings[$k] = $$var;
   }
?>

Settings page in Full

below is the full source of the settings.php page, save this and upload into your theme directory

<?php
$settings = array(
    'youtube' => 'H5h95s0OuEg'
);

# Settings
$themename = "The Web News";
$shortname = "thewebnews";
$options = array (
           array(  "name" => "Main Settings",
                    "type" => "header"
           ),
           array( "name" => "Youtube Video ID",
                  "id" => $shortname."_youtube",
                  "std" => $settings['youtube'],
                  "type" => "text",
                  "note" => "<strong>Example: </strong> http://www.youtube.com/watch?v=<strong style='color: #ff0000;'>H5h95s0OuEg</strong>"
          )
);

function mytheme_add_admin() {
    global $themename, $shortname, $options;
    if ( $_GET['page'] == basename(__FILE__) ) {
        if ( 'save' == $_REQUEST['action'] ) {
                foreach ($options as $value) {
                    if ($value['type']!='header') {
                        update_option( $value['id'], $_REQUEST[ $value['id'] ] );
                    }
                }
                foreach ($options as $value) {
                    if( isset( $_REQUEST[ $value['id'] ] ) ) { update_option( $value['id'], $_REQUEST[ $value['id'] ]  ); } else { delete_option( $value['id'] ); } }

                header("Location: themes.php?page=settings.php&saved=true");
                die;

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

            foreach ($options as $value) {
                delete_option( $value['id'] );
           }
            header("Location: themes.php?page=settings.php&reset=true");
            die;
        }
    }
    add_theme_page($themename." Settings", "Theme Settings", 'edit_themes', basename(__FILE__), 'mytheme_admin');
}
function mytheme_admin() {
    global $themename, $shortname, $options;
    if ( $_REQUEST['saved'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings saved.</strong></p></div>';
    if ( $_REQUEST['reset'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings reset.</strong></p></div>';
?>

<style type="text/css">
th { text-align: left; }
td { padding: 5px 10px !important; }
tr.header {background-color: #99CC66 !important;color: #ffffff;}
.header td {padding: 2px 10px !important;font-size: 14px !important;font-weight: bold !important; }
</style>

<div class="wrap">
 <h2><?php echo $themename; ?> Settings</h2>
  <form method="post">
    <table class="form-table">
      <?php foreach ($options as $value) { if ($value['type'] == "text") { ?>
        <tr>
    	   <th scope="row" style="width: 25%">
               <?php echo $value['name']; ?>:
           </th>
       	   <td>
           <input onfocus="this.select();" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" value="<?php if ( get_settings( $value['id'] ) != "") { echo get_settings( $value['id'] ); } else { echo $value['std']; } ?>" />
&nbsp; &nbsp; <?php echo $value['note']; ?>
     </td>
   </tr>
  <?php } elseif ($value['type'] == "select") { ?>
    <tr>
       <th scope="row"><?php echo $value['name']; ?>:</th>
        <td>
            <select name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>">
                <?php foreach ($value['options'] as $option) { ?>
                <option value="<?php echo $option; ?>" <?php if ( get_settings( $value['id'] ) == $option) { echo ' selected="selected"'; } elseif ($option == $value['std']) { echo ' selected="selected"'; } ?>><?php echo $option; ?></option>
                <?php } ?>
            </select>
&nbsp; &nbsp; <?php echo $value['note']; ?>
        </td>
    </tr>
<?php
} elseif ($value['type'] == "header") {?>
     <tr class="header">
       <td colspan="2">
         <?php  echo $value['name'] ?> &nbsp; &nbsp;
         <span style="font-size: 11px; font-weight: normal;">
            <?php echo $value['note']; ?>
         </span>
       </td>
     </tr>
<?php } } ?>
</table>
<p class="submit">
    <input name="save" type="submit" value="Save changes" />
    <input type="hidden" name="action" value="save" />
</p>
</form>

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

<?php }//end function `mytheme_admin()` ?>

<?php add_action('admin_menu', 'mytheme_add_admin'); ?>

<?php
foreach ($options as $value) {
      if (get_settings( $value['id'] ) === FALSE)
      {
         $$value['id'] = $value['std'];
      } else {
         $$value['id'] = get_settings( $value['id'] );
      }
}

foreach ($settings as $k=>$v) {
   $var = $shortname.'_'.$k;
   if (!empty($$var)) $settings[$k] = $$var;
}
?>

The Javascript

the final addition to the script is using javascript to pull our youtube ID and print the youtube script to the page.
We do this by creating a new javascript file, called “scripts.js” inside this file we save our code below.

function showVideo(id) {
     document.write("<object width=\"269\" height=\"225\"><param name=\"movie\" value=\"http://www.youtube.com/v/"+id+">&amp;hl=en&amp;fs=1\"></param></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"http://www.youtube.com/v/"+id+"&amp;hl=en&amp;fs=1\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"269\" height=\"225\" wmode=\"transparent\"></embed></object>");
}

Display your Video

First thing to do is modify your template header.php file to call our newly created javascript file. include this line below to call that file…

<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/scripts.js"></script>

once that’s done grab your sidebar.php file and call our included script

<script type="text/javascript">showVideo('<?php echo mytheme_settings("youtube") ?>');</script>

Conclusion

With the themes options page, you can start to create more and more functions, to build out your overall site options, ie: create an option to choose colours? choose font size? at this point the limits are endless..

You could go ahead and add as many options as you need, in-order to do what you want…

I hope you find this post useful feel free to leave any comments..

The following two tabs change content below.

Marty

Web Developer
Senior Web Developer who combines passionate coding skills, strategic vision with strong hands on leadership and enormous personal drive. I create re-usable industry standard code that is used time and time again, producing outstanding results for every project I work on! I also like Classic Motorbikes, Quad bikes, Downhill Mountain biking & Learning electronics using the Arduino.

Latest posts by Marty (see all)