之前,我提供了一个指向教程的链接,下面是一个完整的工作示例@mfields示例运行得很好,我的示例只提供了选项字段。
/*
* Single Instance Widget with Options
*/
add_action("widgets_init", array(\'Single_instance_widget\', \'register\'));
register_activation_hook(__FILE__, array(\'Single_instance_widget\', \'activate\'));
register_deactivation_hook(__FILE__, array(\'Single_instance_widget\', \'deactivate\'));
class Single_instance_widget
{
function activate()
{
$data = array(
\'option1\' => \'Default value\',
\'option2\' => 55
);
if (!get_option(\'wpse_1828_widget\'))
{
add_option(\'wpse_1828_widget\', $data);
}
else
{
update_option(\'wpse_1828_widget\', $data);
}
}
function deactivate()
{
delete_option(\'wpse_1828_widget\');
}
function control()
{
$data = get_option(\'wpse_1828_widget\');
echo <<<HTML
<p><label>Option 1<input name="wpse_1828_widget_option1"
type="text" value="{$data[\'option1\']}"/></label></p>
<p><label>Option 2<input name="wpse_1828_widget_option2"
type="text" value="{$data[\'option2\']}"/></label></p>
HTML;
if (isset($_POST[\'wpse_1828_widget_option1\']))
{
$data[\'option1\'] = attribute_escape($_POST[\'wpse_1828_widget_option1\']);
$data[\'option2\'] = attribute_escape($_POST[\'wpse_1828_widget_option2\']);
update_option(\'wpse_1828_widget\', $data);
}
}
function widget($args)
{
echo $args[\'before_widget\'];
echo $args[\'before_title\'] . \'Your widget title\' . $args[\'after_title\'];
echo \'I am your widget\';
echo $args[\'after_widget\'];
}
function register()
{
wp_register_sidebar_widget(\'wpse_1828_widget_id\', \'Single Instance Widget\', array(\'Single_instance_widget\', \'widget\'));
wp_register_widget_control(\'wpse_1828_widget_id\', \'Single Instance Widget\', array(\'Single_instance_widget\', \'control\'));
}
}