How to Create a Better WordPress Options Panel

Today, we'll go through the entire process of creating an admin options panel for a WordPress theme, using the excellent WooFramework as an example. Then, we'll take things a step further, as we implement jQuery to improve some of the functionality.

Tutorial Details

• Program: WordPress
• Version: 2.7, 2.8, 2.9 onwards
• Difficulty: Intermediate
• Estimated Completion Time: 1.5 hours

WordPress is one of the most popular Content Management Software (CMS) systems out there. Whether it be for a client project or for selling themes on ThemeForest, WordPress is fast emerging as a CMS of choice for many web developers. It's relatively easy to use, but can be made even simpler when you include an administration panel for users. Rather than having to open up the PHP template files and fiddling with the code, users can directly use the options panel to interact with your WordPress theme.

For example - if your theme has red, blue and green color schemes, and each has a corresponding CSS file, it would be far easier for a user to select their preferred color from a dropdown list. So today, let me guide you through the entire process of creating and enhancing a WordPress admin panel page inspired by Woo.

Step 1

Before we begin creating the admin panel, we need to have a theme, right? So download the source files provided with the tutorial. I've slightly modified the Classic WordPress theme. Place the 'nettuts' folder (I've named the theme 'Nettuts') in your wp-content/themes folder. You should see the following files:

• functions.php (blank)
• index.php
• footer.php
• rtl.php
• sidebar.php
• style.css
• screenshot.png
• An images folder with two files

Most of our work is going to be done within functions.php file.

A theme can optionally use a functions file, which resides in the theme subdirectory and is named functions.php. This file basically acts like a plugin, and if it is present in the theme you are using, it is automatically loaded during WordPress initialization (both for admin pages and external pages).

Suggested uses for this file:

• Define functions used in several template files of your theme
• Set up an admin screen, giving users options for colors, styles, and other aspects of your theme

Step 2

Now that we've got our WordPress theme set up, go to Appearance>Themes, and activate the nettuts theme.

Activated? Ok, great. Now we have to think of a layout for our admin panel page. Here's the structure I've decided upon:

 1 2 
 3 
 4 
 5 
 6   14 
 15   16  /*Repeat the inputs for as many options as required. */  17  /* use
for each new section of inputs eg General, Home Page etc */  18   19 
 20 


Let me explain all of that to you. The options set is going to be wrapped up into a div named "rm_wrap" and then "rm_opts" for the options. Then we start a form, with all the inputs within it. Each section of options(general Settings, Homepage settings, Blog settings etc) has a separate div with a class of "rm_section". This div has a title (for the name) as well as several input divs within it. By using classes like <div class="rm_input rm_select">, we can style dropdowns, text inputs, and textareas differently.

Now, the most important thing is that the coding of this shouldn't be done manually - we should use PHP's flexibility as much as possible. That means efficiency: don't code manually when you have loops for you!

Step 3

Begin by opening up functions.php in your favorite code editor (I use Notepad++). Enter the following code:

 1 2 

The two PHP variables hold the name of your theme (Nettuts in our case), and a shortname which you've defined (nt in our case). The shortname is used to prefix all our theme options names, and is usually unique to a particular theme. Moving on, we'll write some code to automatically generate a list of WordPress categories, rather than having users type in ID numbers. Enter the code below under the already typed code:

 1 2 $categories = get_categories('hide_empty=0&orderby=name');  3 $wp_cats = array();  4 foreach ($categories as$category_list ) {  5  $wp_cats[$category_list->cat_ID] = $category_list->cat_name;  6 }  7 array_unshift($wp_cats, "Choose a category"); 

This snippet uses WordPress' built-in get_categories function to fetch all categories, and then uses a foreach loop to store them in the variable $wp_cats. The options "Choose a category" is then added to the top of the array Step 4 Now we start entering a list of options for the theme. See below, and paste it into your functions.php file:  1 2 3 $options = array (  4   5 array( "name" => $themename." Options",  6  "type" => "title"),  7   8 9 array( "name" => "General",  10  "type" => "section"),  11 array( "type" => "open"),  12   13 array( "name" => "Colour Scheme",  14  "desc" => "Select the colour scheme for the theme",  15  "id" =>$shortname."_color_scheme",  16  "type" => "select",  17  "options" => array("blue", "red", "green"),  18  "std" => "blue"),  19   20 array( "name" => "Logo URL",  21  "desc" => "Enter the link to your logo image",  22  "id" => $shortname."_logo",  23  "type" => "text",  24  "std" => ""),  25   26   27 array( "name" => "Custom CSS",  28  "desc" => "Want to add any custom CSS code? Put in here, and the rest is taken care of. This overrides any other stylesheets. eg: a.button{color:green}",  29  "id" =>$shortname."_custom_css",  30  "type" => "textarea",  31  "std" => ""),  32   33 array( "type" => "close"),  34 array( "name" => "Homepage",  35  "type" => "section"),  36 array( "type" => "open"),  37 38 array( "name" => "Homepage header image",  39  "desc" => "Enter the link to an image used for the homepage header.",  40  "id" => $shortname."_header_img",  41  "type" => "text",  42  "std" => ""),  43   44 array( "name" => "Homepage featured category",  45  "desc" => "Choose a category from which featured posts are drawn",  46  "id" =>$shortname."_feat_cat",  47  "type" => "select",  48  "options" => $wp_cats,  49  "std" => "Choose a category"),  50   51 52 array( "type" => "close"),  53 array( "name" => "Footer",  54  "type" => "section"),  55 array( "type" => "open"),  56   57 array( "name" => "Footer copyright text",  58  "desc" => "Enter text used in the right side of the footer. It can be HTML",  59  "id" =>$shortname."_footer_text",  60  "type" => "text",  61  "std" => ""),  62   63 array( "name" => "Google Analytics Code",  64  "desc" => "You can paste your Google Analytics or other tracking code in this box. This will be automatically added to the footer.",  65  "id" => $shortname."_ga_code",  66  "type" => "textarea",  67  "std" => ""),  68   69 array( "name" => "Custom Favicon",  70  "desc" => "A favicon is a 16x16 pixel icon that represents your site; paste the URL to a .ico image that you want to use as the image",  71  "id" =>$shortname."_favicon",  72  "type" => "text",  73  "std" => get_bloginfo('url') ."/favicon.ico"),  74   75 array( "name" => "Feedburner URL",  76  "desc" => "Feedburner is a Google service that takes care of your RSS feed. Paste your Feedburner URL here to let readers see it in your website",  77  "id" => $shortname."_feedburner",  78  "type" => "text",  79  "std" => get_bloginfo('rss2_url')),  80 81   82 array( "type" => "close")  83   84 );  That was a large chunk of code, which surely warrants some explanation. So here we go: • The PHP variable$options stores the entire list of options for the theme.
• It is composed of a number of arrays, each with a "type" key to signify how it will be displayed, and what it does.
• We start with a "type" => "title" array - this will be used to show the themename and a title at the top of the page
• Each section (General, Homepage and Footer) has a separate list of options.
• We start a new section by closing any previous sections, declaring a new section using array( "name" => "Footer", "type" => "section") and opening a new section.
• Each option can have the options specified below:
name: The name of the input field.
desc: A short description explaining what it is to the user.
id: the id of the field, prefixed by the shortname. It will be used to store as well as access the options.
type: the input type - select, text or textarea
options: used to declare an array of options for a select type input.
std: the default input value, used if no other input is given.

Step 5

Try navigating to WordPress. You will see that there's no option anywhere to actually view the admin panel page; so how can we view it? Add the following pieces of code to the functions.php file:

 1 2 function mytheme_add_admin() {  3   4 global $themename,$shortname, $options;  5   6 if ($_GET['page'] == basename(__FILE__) ) {  7   8  if ( 'save' == $_REQUEST['action'] ) {  9   10  foreach ($options as $value) {  11  update_option($value['id'], $_REQUEST[$value['id'] ] ); }  12   13 foreach ($options as$value) {  14  if( isset( $_REQUEST[$value['id'] ] ) ) { update_option( $value['id'],$_REQUEST[ $value['id'] ] ); } else { delete_option($value['id'] ); } }  15   16  header("Location: admin.php?page=functions.php&saved=true");  17 die;  18   19 }  20 else if( 'reset' == $_REQUEST['action'] ) {  21   22  foreach ($options as $value) {  23  delete_option($value['id'] ); }  24   25  header("Location: admin.php?page=functions.php&reset=true");  26 die;  27   28 }  29 }  30   31 add_menu_page($themename,$themename, 'administrator', basename(__FILE__), 'mytheme_admin');  32 }  33 34 function mytheme_add_init() {  35 36 } 

This function is meant for updating options, as well as adding a menu page. If the options are being saved (indicated by a hidden variable save), then all the options are updated with their new values. If the options are being reset (indicated by another hidden variable with a value reset), then all of the options are deleted. The last line adds a menu page - the parameters are respectively, name and title, the user authorization level required to view the page, the save page and the function used for display/saving (called mytheme_admin in our case). See the mytheme_add_init, a blanbk function? Let that be, we'll come to it later.

Step 6

Still no theme options page, right? Well, remember the mytheme_admim function we had talked about a few lines ago? We still haven't written that function. So use the code from steps 6,7 and 8 to write that function. Starting off:

 1 2 function mytheme_admin() {  3   4 global $themename,$shortname, $options;  5 $i=0;  6   7 if ( $_REQUEST['saved'] ) echo ' '.$themename.' settings saved.

';  8 if ( $_REQUEST['reset'] ) echo ' '.$themename.' settings reset.

';  9   10 ?>  11 
 12 

Settings

 13   14 
 15 


Pretty simple, right? If the options have been saved, write a message indicating so. Likewise for resets. You'll notice a class="updated fade" - WordPress will automatically fade this out in a few sections. Nifty, right? Moving on, we then start the "rm_wrap" div.

Step 7

Carrying on from above, paste in the following code:

 1 2   7   8   12   13   14   15 
 16 17   18   22 

To easily use the theme, you can use the menu below.

 23 24   25   29 30 
 31   32  " />  33 
 34   35 
 36   41 42 
 43   44   45 
 46   47 
 48   49   54 55 
 56   57   58   62 63 
 64 
 65   70 71 
 72   73   74   75  />  76 77 78 
 79 
 80 

That is one large piece of code! Explanation - using a php foreach loop, each option type is evaluated on a case-by-case basis. We use a switch-case technique for this. The switch variable is the options - the cases are matched and evaluated. Notice the 'break' statement after each case? This is to prevent something known as the 'fall-through' property. When a case is matched, all successive cases are also executed. This means that if we match case 3, cases 4,5 etc. are also executed. We don't wan't that, right? So use a break to stop the switch-case.

If there is an "open" type option - nothing is done. If there is a "close" type options, two divs are closed. The "title" option is only used once - it is an introduction to the theme options. For each of the types "text" (input type="text"), "select" (dropdowns), "checkbox" and "textarea" (its obvious what those mean), the corresponding input is displayed. Notice the <div class="clearfix"> - it's used for clearing floats, which we will do later.

Step 8

We're coming to the end of that rather massive function. Paste in the code below:

 1 2 3 case "section":  4 5 $i++;  6 7 ?>  8 9   10   11   12   13 14   15   20   21   22   23   24   25   26   27   28   29   30   31   32 33   For a "section" type option, I've used a counter variable$i. This keeps track of the sections number and conactenates it to the name of the submit button, to have unique submit buttons. There is also a last form at the end for resetting all options. The image used is going to be a transparent image used in our jQuery-fication. Use this very last piece of code to bring our functions into play:

 1 2  

Step 9

And voila! We have our own awesome admin panel page with a separate menu position for itself. So let's check it out - click the link. And yuck. That has got to be the most ugly admin panel page ever. So let's call upon our good friend, CSS! Create a new folder in the nettuts/ directory and name it "functions". Create a new CSS file there - functions.css. Paste in the following code:

 1 2 .rm_wrap{  3  width:740px;  4 }  5 .rm_section{  6  border:1px solid #ddd;  7  border-bottom:0;  8  background:#f9f9f9;  9 }  10 .rm_opts label{  11  font-size:12px;  12  font-weight:700;  13  width:200px;  14  display:block;  15  float:left;  16 }  17 .rm_input {  18  padding:30px 10px;  19  border-bottom:1px solid #ddd;  20  border-top:1px solid #fff;  21 }  22 .rm_opts small{  23  display:block;  24  float:right;  25  width:200px;  26  color:#999;  27 }  28 .rm_opts input[type="text"], .rm_opts select{  29  width:280px;  30  font-size:12px;  31  padding:4px;  32  color:#333;  33  line-height:1em;  34  background:#f3f3f3;  35 }  36 .rm_input input:focus, .rm_input textarea:focus{  37  background:#fff;  38 }  39 .rm_input textarea{  40  width:280px;  41  height:175px;  42  font-size:12px;  43  padding:4px;  44  color:#333;  45  line-height:1.5em;  46  background:#f3f3f3;  47 }  48 .rm_title h3 {  49  cursor:pointer;  50  font-size:1em;  51  text-transform: uppercase;  52  margin:0;  53  font-weight:bold;  54  color:#232323;  55  float:left;  56  width:80%;  57  padding:14px 4px;  58 }  59 .rm_title{  60  cursor:pointer;  61  border-bottom:1px solid #ddd;  62  background:#eee;  63  padding:0;  64 }  65 .rm_title h3 img.inactive{  66  margin:-8px 10px 0 2px;  67  width:32px;  68  height:32px;  69  background:url('images/pointer.png') no-repeat 0 0;  70  float:left;  71  -moz-border-radius:6px;  72  border:1px solid #ccc;  73 }  74 .rm_title h3 img.active{  75  margin:-8px 10px 0 2px;  76  width:32px;  77  height:32px;  78  background:url('images/pointer.png') no-repeat 0 -32px;  79  float:left;  80  -moz-border-radius:6px;  81  -webkit-border-radius:6px;  82  border:1px solid #ccc;  83 }  84 .rm_title h3:hover img{  85  border:1px solid #999;  86 }  87 .rm_title span.submit{  88  display:block;  89  float:right;  90  margin:0;  91  padding:0;  92  width:15%;  93  padding:14px 0;  94 }  95 .clearfix{  96  clear:both;  97 }  98 .rm_table th, .rm_table td{  99  border:1px solid #bbb;  100  padding:10px;  101  text-align:center;  102 }  103 .rm_table th, .rm_table td.feature{  104  border-color:#888;  105  } 

I won't explain anything here; it's pretty clear what each CSS declaration does, and you're free to customize the layout for your own theme.

Step 10

So now we have a nice CSS file. But how do we add it to the page? After all, we don't have direct access to the <head> of the document. Remember that blank mytheme_add_init() function we wrote in Step 4? That will come in handy. Change it to this:

 1 2 function mytheme_add_init() {  3 $file_dir=get_bloginfo('template_directory');  4 wp_enqueue_style("functions",$file_dir."/functions/functions.css", false, "1.0", "all");  5 } 

That adds the functions.css file to the head. The location of the file is determined by the template directory.

Step 11

Go look at the page now. Pretty nice looking, isn't it? But then, you ask, whats the '+' icon for? Well, thats where jQuery comes in!. Create a new file rm_script.js in the nettuts/functions/ folder. Paste in the following code:

 1 2 jQuery(document).ready(function(){  3  jQuery('.rm_options').slideUp();  4   5  jQuery('.rm_section h3').click(function(){  6  if(jQuery(this).parent().next('.rm_options').css('display')==='none')  7  { jQuery(this).removeClass('inactive').addClass('active').children('img').removeClass('inactive').addClass('active');  8   9  }  10  else  11  { jQuery(this).removeClass('active').addClass('inactive').children('img').removeClass('active').addClass('inactive');  12  }  13   14  jQuery(this).parent().next('.rm_options').slideToggle('slow');  15  });  16 }); 

What this does is - once the DOM loads, all the rm_options slide up. When the '+' icon is clicked, the inactive class is removed from the image and the active class added - making it a '-' icon. The reverse is done when the '-' icon is clicked. The rm_options is then slid up or down(determined by the current CSS state) using the slideToggle function - pretty simple. To add this script, the same mytheme_add_init() function is used. Change it to:

 1 2 function mytheme_add_init() {  3 $file_dir=get_bloginfo('template_directory');  4 wp_enqueue_style("functions",$file_dir."/functions/functions.css", false, "1.0", "all");  5 wp_enqueue_script("rm_script", $file_dir."/functions/rm_script.js", false, "1.0");  6 }  The jQuery script will now be active. Gp check it out. Personally, I think its beautiful! Step 12 Now that we have our theme options page all set up, I'll just run you through using the options. The code to use the options is as follows:  1 2 $var = get_option('nt_colur_scheme'); 

That will fetch the nt_color_scheme options. See the examples below:

 1 2 /* To change the CSS stylesheet depending on the chosen color */  3   4 5 /*To echo some footer copyright text, with HTML */  6 



The variety of uses is limited only by your imagination.

Conclusion

I hope you've learned something in this tutorial. This isn't your standard options panel. This one doesn't use tables, it's jQuery enhanced, uses awesome CSS, and is extremely easy to use. The point of this tutorial is to learn - you could always replace collapsible panels with tabs, for example, or even something more advanced. Use your creativity! Feel free to discuss or ask questions in the comments!

WooThemes has since released version two of their framework. You can review the details here.