最近研究個項目須要在wordpress前端上傳用戶頭像,在網上查了些資料!解決了這個問題!
1:首先就是在須要的地方添加文件上傳框了php
<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: 對圖片進行處理前端
$post=get_post(13);//測試用 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文件添加功能函數wordpress
insert_attachment該函數的第二個參數若是爲空將不附加到文章中圖片。
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' );//因爲頁面刷新的問題直接在頁面使用這個方法是不生效的!須要在函數中構造此方法的功能。 //循環文章中的特徵圖片的方法,若是將圖片附加到文章中使用這個方法能夠批量輸出! $imagess=get_post_meta(13,'wpcf-vi-img',false); foreach($imagess as $images){ echo $images; }