Series links

Building A Theme Options Panel – Part One
Building A Theme Options Panel – Part Two
Building A Theme Options Panel – Part Three
Building A Theme Options Panel – Part Four

Table of contents

  1. Introduction
  2. Saving and Resetting Option Values (wps-panel.php)
  3. Front-end Usage (wps-panel-front.php)

Introduction

Welcome to the 4th part which was planned to be the final one, and it kind of is, the 5th part will be an optional part where we’ll be adding new field types.

But let’s focus on the 4th part now. In this one we’ll handle saving the options in the database and retrieving them in the front end. Let’s get started.

Saving and Resetting Option Values (wps-panel.php)

Time to make some stuff happen when the form is submitted. Let’s take a look at how the wps_panel_init() function looks like at the moment (without the new code).

function wps_panel_init(){
	
	/* Important: There will be more code here, but that will come later on */
	
	/* Add the page */
	add_menu_page('wpsPanel', 'wpsPanel', 'edit_themes', basename(__FILE__), 'wps_panel_output', false, 30);
	
}/* wps_panel_init() */

That’s how we left it back in the 1st part of the series and now we’ll update it. You see where it says /* Important: There will be more code here, but that will come later on */? Well the time has come to put some code in there. Take a look bellow how the new wps_panel_init() function looks like. And don’t worry i’ll explain it right after the snippet.

function wps_panel_init(){
	
	/* Include the options */
	include TEMPLATEPATH.'/wps-panel/wps-panel-options.php';
	 
	/* Save & Reset */
	if (isset($_GET['page']) && $_GET['page'] == basename(__FILE__)) {
		
		/* Save */
		if (isset($_REQUEST['action']) && 'save' == $_REQUEST['action']){
			
			/* Loop the options, cross reference the current and the submitted values, and save if they're different */
			foreach ($options as $option){
				
				if($option['type'] != 'open' && $option['type'] != 'close'){
				
					if(!is_array($_REQUEST[$option['id']])){ $the_value = stripslashes($_REQUEST[$option['id']]); }else{ $the_value = serialize($_REQUEST[$option['id']]); }
					
					if(isset($_REQUEST[$option['id']])){ update_option($option['id'], $the_value); }else{ delete_option($option['id']); } 
					
				}
				
			}
			
			/* Redirect to the theme options page */
			header('Location: admin.php?page=wps-panel.php&saved=true');
			
			/* Chuck Norris */
			die;
		 
		/* Reset */
		}else if(isset($_REQUEST['action']) && 'reset' == $_REQUEST['action']) {
			
			/* Loop the options and delete them (setting the default values will happen on next page load) */
			foreach ($options as $option) {
				delete_option($option['id']); 
			}
			
			/* Redirect to the theme options page */
			header("Location: admin.php?page=wps-panel.php&reset=true");
			
			/* Steven Seagal */
			die;
		 
		}
	}
	
	/* Add the page */
	add_menu_page('wpsPanel', 'wpsPanel', 'edit_themes', basename(__FILE__), 'wps_panel_output', false, 30);
	
}/* wps_panel_init() */

I did add some comments in there so you can understand what happens, but just in case here’s a bit more information.

We need to tell the function what we’re updating, right? It can’t update if it doesn’t know what to update. So first we include the wps-panel-options.php which contains all the info about the options we need.

Then we check what action to take, if you remember we have 2 forms: a little one for resetting and a big one for saving. They both have a hidden input field named action, in the reset form the value is reset and in the save form the value is save (ahhh, if only everything in development was so clear).

If the action is save we loop all the options (wps-panel-options.php) and save the values in the database. If the action is reset it’s the same thing just we delete them from the database instead of saving them in it.

Front-end Usage (wps-panel-front.php)

This is a new file we are going to create. The only thing it will consist of is a function we’ll use to get the option values and store them in an array. Here’s the code.

<?php
/* ---------------------------------------------------------------------------------------------------
 
    File: wps-panel-front.php
 
    Functions for usage in the front-end.
 
--------------------------------------------------------------------------------------------------- */


/* ---------------------------------------------------------------------------------------------------
	wpsPanel GET OPTION VALUES
--------------------------------------------------------------------------------------------------- */
function wps_panel_get_options(){
	
	/* Include the options */
	include TEMPLATEPATH.'/wps-panel/wps-panel-options.php';
	
	/* Create an array */
	$wps_options = array();
	
	/* Loop the options */
	foreach ($options as $option) {
	
		/* If not open or close */
		if($option['type'] != 'open' && $option['type'] != 'close'){
			
			/* If it is not in the database */
			if (get_option($option['id']) === FALSE) { 
				
				/* Get the default value */
				if($option['std'] != ''){
					$wps_options[$option['id']] = $option['std']; 
				}
			
			/* If it is in the database */
			}else{
				
				/* Get the value from the database */
				$option_value = get_option($option['id']);
				if($option_value != ''){
					$wps_options[$option['id']] = $option_value; 
				}
				
			}
		}
	}
	
	/* Return the option values */
	return $wps_options;
	
}/* wps_panel_get_options() END */

?>

All is commented and quite clear i think, if you don’t understand something feel free to ask in the comments.

But now we have to include this file somewhere. Again we’re doing that in the functions.php file of the theme. Remember back in the 1st part when we included the wps-panel.php? Well it’s the same. But let’s improve it a bit. Here’s how it looks now (before modification).

include TEMPLATEPATH.'/wps-panel/wps-panel.php';

…and here is how it looks after modification…

/* Include back-end */
if(is_admin()){ include TEMPLATEPATH.'/wps-panel/wps-panel.php'; }

/* Include front-end */
if(!is_admin()){ include TEMPLATEPATH.'/wps-panel/wps-panel-front.php'; }

As you can see we’re including one file for the back-end and one for the front-end. And we’re using a simple if statement for both, is_admin() is a WordPress function used to determine if we’re in the back-end or not. No need to include unnecessary files, right?

Actual Front-end Usage
<?php
	
	/* Get the options */
	$options = wps_panel_get_options();
	
	/* Actual usage when you need the value */
	echo $options['field_id'];
	
?>
Sample Usage (color style options)

Set the option (wps-panel-options.php).

$options[] = array(	'title' => 'Color Style',
                    'desc'  => 'Here goes the description for this field.',
                    'id'    => $shortname.'_color_style',
					'opts'  => array( 'Light' => 'color-style-light', 'Black' => 'color-style-black', 'Blue' => 'color-style-blue' ),
                    'std'   => 'color-style-light',
                    'type'  => 'select' );

Front end. Getting all the options on top of header.php

<?php
	/* Get the options */
    $options = wps_panel_get_options();
?>

Front end. Setting a class to <body> based on option value.

<body <?php body_class($options['wps_color_style']); ?>>

CSS. Setting rules for the color styles, in style.css

body.color-style-light { /* Rules here */ }
body.color-style-dark { /* Rules here */ }
body.color-style-blue { /* Rules here */ }

Final Words

That’s about it. yulius asked in the comments about a tutorial on adding more fields such as a colorpicker, uploader and such so we’ll be having another part for that. I guess that’ll be the last one.

You can download the files the files for this tutorial, the download link is located on top by the thumbnail. There’s a tweet button too, feel free to tweet about this tutorial. :)

  • authorSlobodan Kustrimovic
  • date17th November 2011
  • views8712
  • comments16 comments

About Author

Slobodan Kustrimovic

I'm a web developer based in a little country called Serbia. Developing WordPress themes is what i like the most and i try to learn more about it every day. I'm the developer behind our WordPress themes and the writer of the Web Development tutorials.

16 Comments

  1. alfi on November 18, 2011 Reply

    Yes, I definitely agree with yulius, for adding, maybe some tut about how to make different layout options so user can change easily dark, light, blue, or something else from opttions panel.

    • boba on November 18, 2011 Reply

      You mean different layout options for the front-end? Simply use a “select” type option with the values like “blue”, “dark”… Then in the front-end in header.php add a class to <body> that represents the style. And in style.css make different rules for different styles.

      • alfi on November 19, 2011 Reply

        Thank you for your response. It is a little bit confuse for me because I am still newbie, maybe some short definitive guide with a little snippet, :) .. Also, I can’t wait for the part 5.. To be honest, your tut on how build options panel is the easiest way to follow, much easier than any others. I have been looking for option page tut but they are hard to follow.

        • boba on November 19, 2011 Reply

          Updated the tutorial, you’ll find what you need at the end of it :)

          • alfi on November 21, 2011

            definitely what I need.. Superb!!

  2. yulius on November 18, 2011 Reply

    Wow, thank you so much boba, you make things clear so far.

    I see many developer make their own path to build the option panel, but the flow is the same, right ??

    What do you think the best practice for beginner to learn about all wp stuff.

    Many Regards.

    Can wait to learn part five… :)

    • boba on November 18, 2011 Reply

      You’re welcome.

      Yeah, some small differences but the “way how it works” is the same.

      The best way is to learn by doing. First download some simple theme and modify it, get to know the WP theme structure. Then try to make your own theme, when you’re stuck somewhere google it, there’s tons of info. And in time you’ll get there.

      Also the WordPress Codex is a gold mine. http://codex.wordpress.org/

      • yulius on November 18, 2011 Reply

        Actually i got a little confuse when i try to learn from the codex (too much link i guess), lol. That’s why i’m looking somewhere else, like wpscientist.
        Btw, nice theme you have boba, good luck with the sales..

        • boba on November 18, 2011 Reply

          Might make a series of tutorials on developing a WordPress theme.

          • yulius on November 19, 2011

            Wonderful..
            Can’t wait that series either.

  3. Birch on December 21, 2011 Reply

    Brilliant. Thank you!

    I looked around for quite a while for something like this, and this is by far the best I encountered. The explanations and comments in the source are both excellent.

    My first proper theme was ready enough to be taken to the next step, user defined colors and stuff, and this tutorial saved me at least a week of research.

    To add a colorpicker and an uploader can’t be too hard compared to this.

    Let’s see if I figure those out before you show us how it should be done,. :-)

  4. Niels De Craecker on January 31, 2012 Reply

    Is it possible to fade in the content when u click a tab?

  5. Zdzichu on February 3, 2012 Reply

    Hi! I need to create a table with textbox. It is simple with your tutorial. But I need to add a new options when all row will be full and i need delete some rows when it is not needed. Can you help me?

  6. Kegan Quimby on February 20, 2012 Reply

    where are the values for the check boxes coming from? if you look in the First Section, down at the bottom “checkbox fields” right next to the checkbox it says “Option Title 2″

    where is this code in the files? where is “Option Title 2″ coming from? the options array is:

    $options[] = array( ‘title’ => ‘Checkbox Fields’,
    ‘desc’ => ‘Here goes the description for this fields.’,
    ‘id’ => $shortname . ‘checkbox_field’,
    ‘std’ => ”,
    ‘type’ => ‘checkbox’ );

  7. sin on March 15, 2012 Reply

    Really great tut, and visually – one of the bests! Very nice code organization, comments in it, everything! Congrats boba!

    Btw can you tell me – this theme options, are all options stored in one row in db, like it is with settings api theme options tuts?

    Thanks in advance!

  8. Cem Demir on June 22, 2012 Reply

    Hi, its really awesome.

    Im using this options panel in a theme. Thanks again !

Leave a Comment

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>