也许这不是你理想的解决方案,但值得一试。通过谷歌搜索得到,但不幸的是我忘记了url。附件与@goldenapples文章中的附件类似。
下面是基本功能。
function attach_uploads($uploads,$post_id = 0){
$files = rearrange($uploads);
if($files[0][\'name\']==\'\'){
return false;
}
foreach($files as $file){
$upload_file = wp_handle_upload( $file, array(\'test_form\' => false) );
$attachment = array(
\'post_mime_type\' => $upload_file[\'type\'],
\'post_title\' => preg_replace(\'/\\.[^.]+$/\', \'\', basename($upload_file[\'file\'])),
\'post_content\' => \'\',
\'post_status\' => \'inherit\'
);
$attach_id = wp_insert_attachment( $attachment, $upload_file[\'file\'], $post_id );
$attach_array[] = $attach_id;
require_once(ABSPATH . \'wp-admin/includes/image.php\');
$attach_data = wp_generate_attachment_metadata( $attach_id, $upload_file[\'file\'] );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
return $attach_array;
}
ajax函数
add_action(\'wp_ajax_attach_file\', \'process_attach_file\');
function process_attach_file() {
// add some filter and validation on the id and the files here
$post_id = $_POST[\'post_id\'];
$files = $_FILES[\'profile-picture\'];
// insert attachment
$attached_files = attach_uploads($files,$post_id);
// set the first file as post thumbnail
if($attached_files){
set_post_thumbnail( $post_id, $attached_files[0] );
}
// now all you have to do is set the response data
}
标记
<form id="upload-form" action="<?php echo admin_url(\'admin-ajax.php\'); ?>" method="post" class="form" enctype="multipart/form-data" >
<label for="profile-picture">Foto Profil</label>
<input type="file" id="profile-picture" name="profile-picture[]" size="40" multiple />
<?php wp_nonce_field( // intention nonce); ?>
<input name="action" value="attach_file" type="hidden">
<input name="post_id" value="12" type="hidden">
</form>
希望这有帮助