我写了一个wordpress插件。我的插件有两个选项。一个是图像上传机制,另一个是复选框。我的代码如下:
<?php
/*
Plugin Name: Plugin Name
Plugin URI:
Description: Description
Version: 0.0.1
Author: Author Name
Author URI:
License: GPL3+
*/
add_action( \'admin_menu\', \'pluginname_menu\' );
function pluginname_menu()
{
add_options_page( \'PluginName Options\', \'pluginname\', \'manage_options\', \'pluginname_options_page\', \'pluginname_options_page\' );
}
add_action( \'admin_init\', \'pluginname_admin_init\' );
function pluginname_admin_init()
{
register_setting( \'pluginname_options\', \'pluginname-settings\' );
add_settings_section( \'section\', \'Section\', \'pluginname_section_callback\', \'pluginname_options-section\' );
$options_array = get_option(\'pluginname-settings\');
add_settings_field( \'upload_image\', \'Upload image\', \'image_upload_callback\', \'pluginname_options-section\', \'section\');
add_settings_field( \'use_image\', \'Use image\', \'use_image_callback\', \'pluginname_options-section\', \'section\', array(
\'name\' => \'pluginname-settings[use_image]\',
\'value\' => isset($options_array[\'use_image\']) ? $options_array[\'use_image\'] : \'\')
);
}
function pluginname_validate($input)
{
$options_array = get_option(\'pluginname-settings\');
$output = array_merge($options_array, $input);
return $output;
}
function pluginname_section_callback()
{
echo \'Feel free to change parameters below.\';
}
function upload_image_callback()
{
echo "<label for=\'image\'>Filename:</label><input type=\'file\' name=\'file\' value=\'image\' />";
}
function use_image_callback( $args )
{
$name = esc_attr( $args[\'name\'] );
$value = esc_attr( $args[\'value\'] );
echo "<input type=\'checkbox\' name=\'$name\' value=\'$value\'>";
}
function pluginname_options_page()
{
$uploadedfile = isset($_FILES[\'file\']) ? $_FILES[\'file\'] : \'\';
if ($uploadedfile[\'error\'] == \'0\')
{
$upload_overrides = array( \'test_form\' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
$options_array = get_option(\'pluginname-settings\');
$options_array[\'upload_image\'] = $movefile[\'url\'];
update_option(\'pluginname-settings\', $options_array);
}
echo "<div class=\'wrap\'>";
echo "<h2>Options</h2>";
echo "<form action=\'options.php\' method=\'POST\' enctype=\'multipart/form-data\'>";
settings_fields( \'pluginname_options\' );
do_settings_sections( \'pluginname_options-section\' );
submit_button(\'Update\', \'primary\', \'submit-form\', false);
echo "</form>";
echo "</div>";
}
?>
我很难以相同的形式使用这两个选项。如果我删除
action=\'options.php\'
, 则不会保存复选框值(不会调用验证函数)。如果我删除
enctype=\'multipart/form-data\'
, 我无法上传。保留所有内容将使选项页完全不可用。请帮忙。