WordPress为此提供了一个方便的功能:wp_handle_upload()
.
假设您在设置页面中已经有相应的文件表单字段,并且您正在使用register_setting()
对于您的选项,因此已经有选项验证回调,只需使用wp_handle_upload()
. 下面是一个示例:
<?php
// Validate file fields
else if ( \'file\' == $optiondetails[\'type\'] ) {
if ( isset( $input[$setting] ) ) {
// Only update setting if input value is in the list of valid options
$setting_file = $setting . \'_file\';
$valid_input[$setting] = ( isset( $_FILES[$setting_file] ) ? theme-slug_image_upload( $setting, $input ) : $valid_input[$setting] );
}
}
?>
那么,你只需要定义一下
theme-slug_image_upload()
回调,使用
wp_handle_upload()
:
<?php
function theme-slug_image_upload( $the_file, $input ) {
$data = $_FILES[$the_file . \'_file\'];
if ( \'\' != $data[\'name\'] )
$upload = wp_handle_upload( $_FILES[$the_file . \'_file\'], array( \'test_form\' => false ) );
else
$upload[\'url\'] = $input[$the_file];
return $upload[\'url\'];
}
?>
差不多就是这样。