How add options to your WordPress 2.7 dashboard widgets

Well, in this article, I assume you have read the WP Engineer's excellent post Add WordPress Dashboard Widgets, because his code will be our start point.

So, we have this code:

 
 
// Load up the localization file if we're using WordPress in a different language
// Place it in this plugin's folder and name it "MainFunction-[value in wp-config].mo"
load_plugin_textdomain( 'MainFunction', '/wp-content/plugins/MainFunction' );
 
/**
 * Content of Dashboard-Widget
 */
function MainFunction() {
	echo 'Test Add Dashboard-Widget';
}
 
/**
 * add Dashboard Widget via function wp_add_dashboard_widget()
 */
function MainFunction_Init() {
	wp_add_dashboard_widget( 'MainFunction', __( 'MainFunction Widget Title' ), 'MainFunction' );
}
 
/**
 * use hook, to integrate new widget
 */
add_action('wp_dashboard_setup', 'MainFunction_Init');
 

OK, now, remenber the wp_add_dashboard_widget function?

function wp_add_dashboard_widget( $widget_id, $widget_name, $callback, $control_callback = null )

The $control_callback parameter (obviously optional) is our main target. It gives the 'Configure' option to our spiffy widget.
So, we need to add a 4th parameter to wp_add_dashboard_widget:

wp_add_dashboard_widget( 'MainFunction', __( 'MainFunction Widget Title' ), 'MainFunction', 'MainFunction_Setup');

The MainFunction_Setup function handles two things: the options (set the default options, recolect new values, etc) and the option's presentation (i.e. the HTML part)

So, here goes the code:

 
 
function MainFunction_Options() {
	$defaults = array( 'items' => 5, 'boolean' => 1);
	if ( ( !$options = get_option( 'MainFunction' ) ) || !is_array($options) )
		$options = array();
	return array_merge( $defaults, $options );
}
 
function MainFunction_Setup() {
 
	$options = MainFunction_Options();
 
	if ( 'post' == strtolower($_SERVER['REQUEST_METHOD']) && isset( $_POST['widget_id'] ) && 'MainFunction' == $_POST['widget_id'] ) {
		foreach ( array( 'items', 'boolean' ) as $key )
				$options[$key] = $_POST[$key];
		update_option( 'MainFunction', $options );
	}
 
?>
 
 
		<label for="items"><PHP _e('How many items?', 'MainFunction' ); ?>
<select id="items" name="items">
				<PHP
					for ( $i = 5; $i <= 20; $i = $i + 1 )
						echo "
<option value='$i'" . ( $options['items'] == $i ? " selected='selected'" : '' ) . ">$i</option>
 
";
				?>
			</select>
 
		</label>
 
 
 
		<label for="boolean">
<input id="boolean" name="boolean" type="checkbox" value="1"<PHP if ( 1 == $options['boolean'] ) echo ' checked="checked"'; ?> />
			<PHP _e('Activate boolean?', 'MainFunction' ); ?>
		</label>
 
 
<PHP
 }
 

As you can see, MainFunction_Options puts the default values (if necessary, of course) and MainFunction_Setup show the current values and let change them. You can merge this two, of course...

Now, we have to get the options and use them in our MainFunction function. Change MainFunction like that:

 
/**
 * Content of Dashboard-Widget
 */
function MainFunction() {
 
        $widget_options = MainFunction_Options();
 
	echo 'Test Add Dashboard-Widget';
	echo "You have selected $widget_options['items'] items";
	echo "boolean is $widget_options['boolean']";
 
}
 

The complete code here:

 
<PHP
 
// Load up the localization file if we're using WordPress in a different language
// Place it in this plugin's folder and name it "MainFunction-[value in wp-config].mo"
load_plugin_textdomain( 'MainFunction', '/wp-content/plugins/MainFunction' );
 
/**
 * Content of Dashboard-Widget
 */
function MainFunction() {
        $widget_options = MainFunction_Options();
 
	echo 'Test Add Dashboard-Widget';
	echo "You have selected $widget_options['items'] items";
	echo "boolean is $widget_options['boolean']";
}
 
/**
 * add Dashboard Widget via function wp_add_dashboard_widget()
 */
function MainFunction_Init() {
	wp_add_dashboard_widget( 'MainFunction', __( 'MainFunction Widget Title' ), 'MainFunction' , 'MainFunction_Setup' );
}
 
function MainFunction_Options() {
	$defaults = array( 'items' => 5, 'boolean' => 1);
	if ( ( !$options = get_option( 'MainFunction' ) ) || !is_array($options) )
		$options = array();
	return array_merge( $defaults, $options );
}
 
function MainFunction_Setup() {
 
	$options = MainFunction_Options();
 
	if ( 'post' == strtolower($_SERVER['REQUEST_METHOD']) && isset( $_POST['widget_id'] ) && 'MainFunction' == $_POST['widget_id'] ) {
		foreach ( array( 'items', 'boolean' ) as $key )
				$options[$key] = $_POST[$key];
		update_option( 'MainFunction', $options );
	}
 
?>
 
 
		<label for="items"><PHP _e('How many items?', 'MainFunction' ); ?>
<select id="items" name="items">
				<PHP
					for ( $i = 5; $i <= 20; $i = $i + 1 )
						echo "
<option value='$i'" . ( $options['items'] == $i ? " selected='selected'" : '' ) . ">$i</option>
 
";
				?>
			</select>
 
		</label>
 
 
 
		<label for="boolean">
<input id="boolean" name="boolean" type="checkbox" value="1"<PHP if ( 1 == $options['boolean'] ) echo ' checked="checked"'; ?> />
			<PHP _e('Activate boolean?', 'MainFunction' ); ?>
		</label>
 
 
<PHP
 }
 
/**
 * use hook, to integrate new widget
 */
add_action('wp_dashboard_setup', 'MainFunction_Init');
 
?>
 

You can view a PHPS version (without PHP crippled tags) here.


16 Comentarios

  1. G

    Finally you get it. Thanks, I didn’t know how to do it. ;)

    #1 artberri [2009/02/01 @ 20:31] Reply to artberri
  2. G

    Perfecto! es exactamente lo que buscaba… :-)

    #2 kolom [2009/03/18 @ 21:10] Reply to kolom
  3. G

    Hi,
    I used your codes but there is no ‘Edit’ link anywhere. Can you add an image your dashboard widget, please.

    #3 Yakup Gövler [2009/05/23 @ 13:19] Reply to Yakup Gövler
  4. G

    If I buy an original Iphone off ebay, and then just put my sim card in, how much will I be charged monthly? My current plan had unlimited data, texts, and shared 750 minutes. Will I have to pay more?

    ________________
    [url=http://www.youtube.com/watch?v=kgEab0gxRkM]unlock iphone[/url]

    #4 Neusa [2009/10/29 @ 23:50] Reply to Neusa
  5. G

    [b]Are you mastering the art of putting together your own DJ mix? [/B]

    [b]MyDjSpace.net[/b]
    If you are like a lot of people you have longed to be
    a DJ for a long time but just aren’t positive how to put together a a winning DJ mix.

    What if you could get online and instantly communicate with others who could
    help you?

    What if you could become a member of a center that
    is so grand that you can voice your headaches and problems and get
    help from people who know thier stuff?

    If you would like all of this and more then you should surely check out mydjspace.net where you can get all of this and more!

    Join [URL=http://mydjspace.net]DJ Mix Download[/URL]

    _________________
    [URL=http://satmods.com][b]FTA HD[/b][/URL]

    #5 Endeamyagoday [2009/10/29 @ 23:52] Reply to Endeamyagoday
  6. G

    hi. im trying to add a text widget of widgets sidebar in dashboard. how can i do it? anyone can help me, please!!

    #6 marujo [2009/12/21 @ 23:32] Reply to marujo
  7. G

    Your call to load_plugin_textdomain has a hardcoded plugin location.

    load_plugin_textdomain( ‘MainFunction’, ‘/wp-content/plugins/MainFunction’ );

    should be something like

    load_plugin_textdomain( ‘MainFunction’, false, dirname( plugin_basename( __FILE__ ) ) );

    See http://codex.wordpress.org/Function_Reference/load_plugin_textdomain

    #7 Andy from Workshopshed [2011/08/03 @ 12:34] Reply to Andy from Workshopshed
  8. G

    Android News Телефоны Nokia, Google, Apple, рынок мобильных устройств Windows 8 mobile News мобильные обзоры Новости Samsung Каталог мобильных устройств куплю телефон,купить телефон

    #8 iphone52012 [2012/01/07 @ 21:34] Reply to iphone52012
  9. G

    If you have some spare time, You can visit these forums:

    Hosting forum – TopHostingForum.com
    Gaming forum – CellyForum.com
    Health forum – ForumHealth.net

    #9 Occacualmla [2012/01/19 @ 02:44] Reply to Occacualmla
  10. G

    Bravo, seems excellent idea to me is
    [url=http://www.sexfg.com/]lesviako free video[/url] [url=http://www.outporn.com/]mobile download free fucking videos[/url]

    #10 Amateurbasketba [2012/01/19 @ 04:14] Reply to Amateurbasketba
  11. G

    If You got some free time, you can check these Forums:

    Hosting forum – TopHostingForum.com
    Gaming Forum – CellyForum.com
    Health forum – ForumHealth.net

    #11 Occacualmua [2012/01/19 @ 05:47] Reply to Occacualmua
  12. G

    [url=http://www.who.is/whois/torbypapierowe.info.pl]Torby papierowe[/url]
    [url=http://www.webutation.net/go/review/torbypapierowe.info.pl]Torby papierowe[/url]
    [url=http://www.kaboodle.com/store/torbypapierowe.info.pl]Torby papierowe[/url]
    [url=http://who.is/whois/torbypapierowe.info.pl]Torby papierowe[/url]
    [url=http://www.quantcast.com/torbypapierowe.info.pl]Torby papierowe warszawa[/url]

    #12 musymumbSot [2012/01/19 @ 06:30] Reply to musymumbSot
  13. G

    best for you chanel bags prices , just clicks away fxwinter20off

    #13 Roottsed [2012/01/19 @ 07:00] Reply to Roottsed
  14. G

    We are founded in 2010 and located in HongKong. sabosaleau.com is an online e-commerce company offering tens of thousands of popular jewelry products including Thomas Sabo Pendant, Thomas Sabo Bracelets, Thomas Sabo Necklaces, Thomas Sabo Earrings, Thomas Sabo Rings, Thomas Sabo Watches, Thomas Sabo Chains, Thomas Sabo Carriers and also include the Thomas Sabo Birth Stones, Thomas Sabo Letters Charm, Thomas Sabo Love Charms, Thomas Sabo Rebel at Heart, Thomas Sabo Seasonal, Thomas Sabo Classic. Purchasing from us, you can get more 10-70% off than other website.[url=http://www.sabosaleau.com]Thomas Sabo[/url].

    #14 ailunsi [2012/01/19 @ 07:01] Reply to ailunsi
  15. G

    If you have some spare time, You can visit these Forums:

    Hosting Forum – TopHostingForum.com
    Gaming forum – CellyForum.com
    Health forum – ForumHealth.net

    #15 Occacualmua [2012/01/19 @ 08:47] Reply to Occacualmua
  16. G

    Prior to closing, when I simply raise the real antiquing Gol Diamond, Antique silver is fairly typical in the industry today and is the effective exercise of the completion of a ne method for silver that a large supply of external visual appea age.The first thing you want to make sure Äôll after years of selling diamonds links London is without doubt the cleanliness

    Sterling silver rings are so popular probably available in any store in the links of London. Select generall things are also a God of talented people and that is beauty. Which allows a person to do, you can use the natural elegance, AOT will be inherited by all means. Although, there are specific resources to look stunning. Putting on a costume is good only on e great means looking beautiful. Your persona of a person is most exposed and evaluated with all other accessories for dressing [b]ugg boots classic tall[/b] g up style. But, the most beautiful jewel AOS every time Donne, it does not make a person beautiful appearance Simpl and ALS makes him look distinctive, different and observable. It’s just diamond. Because it is a kind of personal decoration, it, AOS describe, because the group, necklace, earrings and more.

    When you search online but there are plenty of silver sweetie bracelet links sites to choose from. Mancheste around the worl will recognize as a result of e jewelr diamond. Day after day the true recognition involvin diamond jewelr in Mancheste will improve and for that reason, you find [url=http://www.classictalluggboots.org.uk]ugg boots classic tall[/url] ugg boots classic tall m such a variety o advancemen in thi area. Trend as diamond jewelr is certainly not limited just to women but men inspired you towards anyone, and so we come to the aid of the best diamonds in Mancheste jewelr. At present anyone the easiest way of having your choice of diamond jewelr sit inside your house through our own diamonds sit inside jewelr Mancheste. While usin improving public access and as an alternative we provide to you in diamonds jewelr thei best when thinking about every single kind of distinctive tastes and wishes of individuals involvin current era.

    go through their products and communicate with one’s own workforce links friendship bracelet personalized In case you think that the jewelry can best gift you can with your family, Hubb, partne share and right, you tend to be absolutely correct. Precious gemstone best describe the wonderful sensation of real worship. You could get excellent designs and styles for every little thing you can ask.

    buys fewer methods of brides very cheap links of london sweetie acquired bracelet From heavy bridal jewelry to your child, AOS anklets, you can fin almost anything with the jewels birmingham. Moreove, we now Anklet bracele and even within Stee, if you, especially with regard to the Aore. Precious diamond earring, rings (men or women), these are some question you may get confused as a result o the availability of unique and beautiful pattern.

    This entry was posted on Monday, December 26, 2011 at 10:09 p.m. and is filed under Links Of London Stores. You can follow any responses to this entry through the RSS 2.0 feed. Comments are currently closed, but you can trackback from your own site.

    #16 woodhzan [2012/01/31 @ 22:49] Reply to woodhzan

6 Trackbacks/Pingbacks

  1. F

    [...] Nice to read: a update of this post to include options in the dashboard widget: How add options to your WordPress 2.7 dashboard widgets [...]

    Pingback: Add WordPress Dashboard Widgets - Test My Dashboard, ID, first parameter, second parameter, name, third parameter - WP Engineer [2009/02/11 @ 11:40]
  2. F

    [...] How to add options to your wordpress 2.7 dashboard widgets [...]

    Pingback: Wordpress Wednesday: The Trilogy [2010/03/13 @ 08:38]
  3. F

    [...] How to add options to your wordpress 2.7 dashboard widgets [...]

    Pingback: RegexHacks » Wordpress Wednesday: The Trilogy [2010/12/16 @ 08:30]
  4. F

    [...] How to add options to your wordpress 2.7 dashboard widgets [...]

    Pingback: Wordpress Wednesday: The Trilogy | Logo Design Virginia [2011/01/25 @ 14:51]
  5. F

    [...] How to add options to your wordpress 2.7 dashboard widgets [...]

    Pingback: Wordpress Wednesday: The Trilogy | Ascend Social Media Marketing [2011/08/18 @ 07:47]
  6. F

    [...] How to add options to your wordpress 2.7 dashboard widgets [...]

    Pingback: Wordpress Wednesday: The Trilogy | autoblog [2011/11/22 @ 03:17]

Participa: