The register_setting
function saves the value attribute on form submission directly into the database. We can also alter or validate the value based on our choice. The register_setting
function takes a third argument which is a callback, this callback is fired before it saves the settings into the database.
For uploading files through settings pages we can handle the uploads via the callback and then store the URL to the file in dbms. Here is example code showing how to do that;
function demo_settings_page()
{
add_settings_section("section", "Section", null, "demo");
add_settings_field("demo-file", "Demo File", "demo_file_display", "demo", "section");
register_setting("section", "demo-file", "handle_file_upload");
}
function handle_file_upload($option)
{
if(!empty($_FILES["demo-file"]["tmp_name"]))
{
$urls = wp_handle_upload($_FILES["demo-file"], array('test_form' => FALSE));
$temp = $urls["url"];
return $temp;
}
return $option;
}
function demo_file_display()
{
?>
<input type="file" name="demo-file" />
<?php echo get_option('demo-file'); ?>
<?php
}
add_action("admin_init", "demo_settings_page");
function demo_page()
{
?>
<div class="wrap">
<h1>Demo</h1>
<form method="post" action="options.php">
<?php
settings_fields("section");
do_settings_sections("demo");
submit_button();
?>
</form>
</div>
<?php
}
function menu_item()
{
add_submenu_page("options-general.php", "Demo", "Demo", "manage_options", "demo", "demo_page");
}
add_action("admin_menu", "menu_item");
Here is a screenshot of the settings page