最近研究個(gè)專(zhuān)案需要在wordpress前端上傳使用者頭像,在網(wǎng)路上查了些資料!解決了這個(gè)問(wèn)題!
1:首先就是在需要的地方新增檔案上傳框了
<form action="" method="post" enctype="multipart/form-data"> ????<input type="file" id="file" name="files[]" multiple="multiple" accept="image/*" /> ??<input type="submit" name="submit" value="Upload!" /> </form>
2: 對(duì)圖片進(jìn)行處理
$post=get_post(13);//測(cè)試用 if?(?$_FILES?)?{ ????$files?=?$_FILES['files']; ?????$count=?count($files['name']); ????foreach?($files['name']?as?$key?=>?$value)?{ ????????if?($files['name'][$key])?{ ????????????$file?=?array( ????????????????'name'?????=>?$files['name'][$key], ????????????????'type'?????=>?$files['type'][$key], ????????????????'tmp_name'?=>?$files['tmp_name'][$key], ????????????????'error'????=>?$files['error'][$key], ????????????????'size'?????=>?$files['size'][$key] ????????????); ????????????$_FILES?=?array("files"?=>?$file); ????????????foreach?($_FILES?as?$file?=>?$array)?{ ????????????????$newupload?=?insert_attachment($file,$post->ID);//此方法將文章附加到ID為13的文章中。如果不想插入到文章可以為空"" }?}?}?}
3:在functions.php檔案中新增功能函數(shù)
#insert_attachment該函數(shù)的第二個(gè)參數(shù)如果為空將不附加到文章中圖片。
function?insert_attachment($file_handler,$post_id,$setthumb='false')?{ ?global?$wpdb; ??//?check?to?make?sure?its?a?successful?upload ??if?($_FILES[$file_handler]['error']?!==?UPLOAD_ERR_OK)?__return_false(); ??require_once(ABSPATH?.?"wp-admin"?.?'/includes/image.php'); ??require_once(ABSPATH?.?"wp-admin"?.?'/includes/file.php'); ??require_once(ABSPATH?.?"wp-admin"?.?'/includes/media.php'); ??$attach_id?=?media_handle_upload(?$file_handler,?$post_id?); $image_url?=?wp_get_attachment_image_src(??$attach_id,'full'?);? if?($setthumb){? ??$wpdb->insert( ??$wpdb->prefix?.?'postmeta',?array( ????????????????'post_id'?=>?$post_id, ????????????????'meta_key'?=>?'wpcf-vi-img', ????????????????'meta_value'?=>?$image_url[0]?)); ??} ??return?$attach_id; }
4:引用方法
$image_url?=?wp_get_attachment_image_src(??$attach_id,'full'?);//由于頁(yè)面刷新的問(wèn)題直接在頁(yè)面使用這個(gè)方法是不生效的!需要在函數(shù)中構(gòu)造此方法的功能。 //循環(huán)文章中的特征圖片的方法,如果將圖片附加到文章中使用這個(gè)方法可以批量輸出! $imagess=get_post_meta(13,'wpcf-vi-img',false); foreach($imagess?as?$images){ ?echo??$images; }