WordPress Tutorial: Add an Options page to your WP theme

MySuperTheme-Options-WordPress

Have you built your own wordpress theme and now would like to add flexibility by allowing the admin to customize parts of it? Then what you need is an Options page within the WP admin side. Now you’re thinking “OMG, admin side? That’s much too complex for me!!!”. FALSE! Believe me: read this tutorial, and then you’ll be able to add any kind of option to your theme!

So, ready for some PHP? Let’s go!

In this tutorial, I’ll customize a theme named MySuperTheme. I’ll add an Options page to allow the admin to embed his/her video on the home page.

First step: the back-end.
Open the functions.php file in your theme’s directory (here I need to go to /wp-content/themes/MySuperTheme/) and add these 2 variables:

/**********************************
 *  Options page for the theme
 **********************************/

// the name of the theme
$themename = "MySuperTheme";

// an abbreviation of the theme's name
$shortname = "mst";

Now you’ve need to declare an array with the options you wish to have. Each option is made of an array containing the following elements:

  • name: the name of the option, also displayed on the admin options page
  • desc: a description of the option, displayed on the options page to help the admin to know what/how he/she has to set
  • id: a unique id for the option. To have logic in our code, all ids begin with the $shortname value
  • type: the type of option you want to display. It can be set to “text” if you want to display a text field, “checkbox” if you want to display a checkbox, “textarea”, “listbox”, … Another value can be given: “heading”, which will display a title on the options page, which can be useful if have many sections with titles.
  • std: the default value
  • options: an array of properties for the displayed element. For example, the “cols” and “rows” properties of a textarea, or the “options” for a listbox, …

Following is the code for my Options page with video embedding:

// options
$options = array (

	// the title of the section
	array (	"name" => "Front page - Video",
			"type" => "heading" ),

	// a checkbox set on / off the display of the video
	array (	"name"		=> "Display a video on the front page?",
			"id"		=> $shortname . "_video_enabled",
			"type"		=> "checkbox",
			"std"		=> false ),

	// a textarea where the admin can enter the code of the embedded video
	array ( "name"		=> "Code",
			"desc"		=> "Enter the code for the video you want to display on your front page",
			"id"		=> $shortname . "_video_code",
			"std"		=> '<object width="895" height="525">
<param name="movie" value="http://www.youtube.com/v/w0ffwDYo00Q&hl=en&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999&hd=1&showinfo=0"></param>
<param name="allowFullScreen" value="true"></param>
<param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube.com/v/w0ffwDYo00Q&hl=en&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999&hd=1&showinfo=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="895" height="525"></embed>
</object>',
			"type"		=> "textarea",
			"options"	=> array (	"cols" => 80,
									"rows" => 10 )),

	// a text field to give a name to display for the video
	array ( "name"		=> "Title",
			"desc"		=> "Enter the title to display for the video",
			"id"		=> $shortname . "_video_title",
			"std"		=> "My Video",
			"type"		=> "text" )

);

Now we have to add the function which build the options admin page…

// create the Options page on the admin side
function mytheme_add_admin() {

	global $themename, $shortname, $options;

	if ( $_GET['page'] == basename(__FILE__) ) {

		// save options values
		if ( 'save' == $_REQUEST['action'] ) {

			foreach ($options as $value) {
				if ($value['type'] != 'multicheck') {
					update_option( $value['id'], $_REQUEST[ $value['id'] ] );
				} else {
					foreach ($value['options'] as $mc_key => $mc_value){
						$up_opt = $value['id'].'_'.$mc_key;
						update_option($up_opt, $_REQUEST[$up_opt] );
					}
				}
			}

			foreach ($options as $value) {
				if ($value['type'] != 'multicheck') {
					if ( isset( $_REQUEST[ $value['id'] ] ) ) {
						update_option( $value['id'], $_REQUEST[ $value['id'] ]  );
					} else {
						delete_option( $value['id'] );
					}
				} else {
					foreach ($value['options'] as $mc_key => $mc_value){
						$up_opt = $value['id'].'_'.$mc_key;
						if ( isset( $_REQUEST[ $up_opt ] ) ) {
							update_option( $up_opt, $_REQUEST[ $up_opt ]  );
						} else {
							delete_option( $up_opt );
						}
					}
				}
			}
			header("Location: themes.php?page=functions.php&saved=true");
			die;

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

			foreach ($options as $value) {
				if ($value['type'] != 'multicheck') {
					delete_option( $value['id'] );
				} else {
					foreach($value['options'] as $mc_key => $mc_value) {
						$del_opt = $value['id'].'_'.$mc_key;
						delete_option($del_opt);
					}
				}
			}
			header("Location: themes.php?page=functions.php&reset=true");
			die;
		}

	}

	// Add Options page to the admin menu
	add_theme_page($themename." Options", "$themename Options", 'edit_themes', basename(__FILE__), 'mytheme_admin');
}

… and a function to create the Options page content.

// build the Options page
function mytheme_admin() {

	global $themename, $shortname, $options;

	// Display message after saving / resetting options' values
	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>';

?>
<div class="wrap">
	<h2> settings</h2>
	<form method="post">
		<table class="optiontable">

<?php foreach ($options as $value) { 

	// retrieve the 'type' value in the option array
	switch ( $value['type'] ) {

		// if the option's value is contained in a text field
		case 'text':
			option_wrapper_header($value);
			?>
				<input style="width:400px;" 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']; } ?>" />
			<?php
			option_wrapper_footer($value);
			break;

		// if the option's value is a selected value from a menu list
		case 'select':
			option_wrapper_header($value);
			?>
	                $lt;select style="width:240px;" name="$lt;?php echo $value['id']; ?>" id="$lt;?php echo $value['id']; ?>">
				$lt;?php foreach ($value['options'] as $option) { ?>
				<option<?php if ( get_settings( $value['id'] ) == $option) { echo ' selected="selected"'; } elseif ($option == $value['std']) { echo ' selected="selected"'; } ?>><?php echo $option; ?></option>
				<?php } ?>
	                </select>
			<?php
			option_wrapper_footer($value);
			break;

		// if the option's value is contained in a textarea
		case 'textarea':
			$ta_options = $value['options'];
			option_wrapper_header($value);
			?>
			<textarea name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" cols="<?php echo $ta_options['cols']; ?>" rows="<?php echo $ta_options['rows']; ?>">
			<?php if ( get_settings($value['id']) != "") {
				echo get_settings($value['id']);
			} else {
				echo $value['std'];
			} ?></textarea>
			<?php
			option_wrapper_footer($value);
			break;

		// if the option's value is a selected value from a radio button
		case "radio":
			option_wrapper_header($value);
	 		foreach ($value['options'] as $key=>$option) {
				$radio_setting = get_settings($value['id']);
				if ($radio_setting != '') {
		    		if ($key == get_settings($value['id']) ) {
						$checked = "checked=\"checked\"";
						} else {
							$checked = "";
						}
				} else {
					if($key == $value['std']){
						$checked = "checked=\"checked\"";
					} else {
						$checked = "";
					}
				}?>
		        <input type="radio" name="<?php echo $value['id']; ?>" value="<?php echo $key; ?>" <?php echo $checked; ?> /><?php echo $option; ?><br />
	 		<?php
			}
			option_wrapper_footer($value);
			break;

		case "checkbox":
			option_wrapper_header($value);
	 		if(get_settings($value['id'])){
				$checked = "checked=\"checked\"";
	 		}else{
				$checked = "";
	 		}
	 		?>
	 		<input id="<?php echo $value['id']; ?>" name="<?php echo $value['id']; ?>" type="checkbox" value="true" <?php echo $checked; ?> />
			<?php
			option_wrapper_footer($value);
			break;

		case "multicheck":
			option_wrapper_header($value);
	 		foreach ($value['options'] as $key=>$option) {
	 		$pn_key = $value['id'] . '_' . $key;
	 		$checkbox_setting = get_settings($pn_key);
	 		if ($checkbox_setting != '') {
		    		if (get_settings($pn_key) ) {
						$checked = "checked=\"checked\"";
					} else {
						$checked = "";
					}
				} else {
					if ($key == $value['std']) {
						$checked = "checked=\"checked\"";
					} else {
						$checked = "";
					}
				}?>
	 		<input type="checkbox" name="<?php echo $pn_key; ?>" id="<?php echo $pn_key; ?>" value="true" <?php echo $checked; ?> /><label for="<?php echo $pn_key; ?>"><?php echo $option; ?></label><br />
			<?php
			}
			option_wrapper_footer($value);
			break;

		// if the option's value is the title of a section in the Options page
		case "heading":
			?>
			<tr valign="top">
			    <td colspan="2" style="text-align: center;"><h3><?php echo $value['name']; ?></h3></td>
			</tr>
			<?php
			break;

		default:
			break;
	}
}
?>
		</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">
			<input name="reset" type="submit" value="Reset" />
			<input type="hidden" name="action" value="reset" />
		</p>
	</form>
</div>
<?php
}

// create option's name
function option_wrapper_header($values){
	?>
	<tr valign="top">
	    <th scope="row"><?php echo $values['name']; ?>:</th>
	    <td>
	<?php
}

// create option's description
function option_wrapper_footer($values){
	?>
	    </td>
	</tr>
	<tr valign="top">
		<td> </td><td><small><?php echo $values['desc']; ?></small></td>
	</tr>
	<?php
}

Finally, we have to activate our Option’s page.

// enable the Options page
add_action('admin_menu', 'mytheme_add_admin');

Now we have built an Option page for our theme! This page is located under the Appearance menu on the admin side.

MySuperTheme-Options-Wordpress-Site-WordPress

Second step: the front-end

Now that we have created our Options page, we need to adapt our theme to use these options. We simply need to retrieve the values of the options using the get_option call code and display the elements in our theme.

In my example, I wanted to embed a video on my front page. This means I need to edit the index.php file of my theme (it could also be known as home.php).

  • add a new div if the “Display a video on the front page?” checkbox is checked
  • in this new div insert the code for the video
  • add a caption to the video

Here is the code to include where the video needs to be inserted:

<?php if (get_option('mst_video_enabled')) {	// the following code is processed if the box is checked
		echo '<div class="video-box">';	// create the div
		echo get_option('mst_video_code');	// insert the code
		echo '<p class="video-title">' . get_option('mst_video_title') . '</p>';	// insert the caption
		echo '</div>';
	}
?>

And now we have a video displayed on the front page!

Page-Image

Build your own Options pageNow that you’ve learned how to add an Options page to your theme, express your creativity and add options to your own theme!

share

Tags: , ,

21 Responses to “WordPress Tutorial: Add an Options page to your WP theme”

  1. [...] This post was mentioned on Twitter by Amélie Husson, JeanneBernish. JeanneBernish said: RT @Othella: #Wordpress #Tutorial: Add an Options page to your WP theme http://bit.ly/4rXGrG [...]

  2. Social comments and analytics for this post…

    This post was mentioned on Twitter by Othella: #Wordpress #Tutorial: Add an Options page to your WP theme http://bit.ly/4rXGrG

  3. [...] Add an options page to your WordPress theme [...]

  4. [...] Theme Options VITALI-SOFTWARE WP SCOOP PRO BLOG DESIGN BLOGSESSIVE CSS REFLEX FOR THE [...]

  5. suizeo says:

    thank you very much

  6. [...] WordPress Tutorial: Add an Options page to your WP theme [...]

  7. Buster Winik says:

    Who made this wp concept? Can I’ve his/her make contact with e-mail or IM identify?

  8. this is a very helpful post, i already included it on my bookmark thanks

  9. lastminute says:

    lastminute…

    [...]Wordpress Tutorial: Add an Options page to your WP theme | vitali software[...]…

  10. [...] For Your WordPress Theme 6.Creating Custom Write Panels in WordPress 7.Thematic Options Panel 8.Add an Options page to your WP theme 9.WordPress Theme Settings Page 10.How to create a WordPress Theme Options Page 11.How To Add A [...]

  11. what is adapalene…

    [...]Wordpress Tutorial: Add an Options page to your WP theme | vitali software[...]…

  12. [...] Theme Options Vitali-Software WP Scoop Pro Blog Design Blogsessive CSS Reflex For The [...]

Leave a Reply


Men are from Mars. Women are from Venus. Computers are from hell.

Unknown


NEWS

Wir suchen nach einem motivierter und dynamischer Webentwickler (Ruby on Rails Kenntnisse erforderlich, dazu PHP/.Net Kenntnisse wären ein Bonus)! Bewerben Sie sich jetzt! (Büro in Gerlingen)


CONTACT

Do you need more information or a quote? Fill the following form and we'll answer you within 24 hours!