2017-10-21 91 views
1

我想添加一個表單在wordpress中的用戶配置文件管理頁面中上傳圖像,我以前試過這個代碼,它在正常的php頁面中工作正常,但是當我嘗試它在這個WordPress的功能,它不工作。無法在wordpress管理頁面上傳圖像

有人可以幫忙嗎?

function image_up_gall(){ 
?> 
    <form action="#" method="post" enctype="multipart/form-data"> 
    Select image to upload: 
    <input type="file" name="fileToUpload" id="fileToUpload"> 
    <input type="submit" value="Upload Image" name="submit"> 
    </form> 

<?php 
$target_dir = "uploads/"; 
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); 
$uploadOk = 1; 
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 
// Check if image file is a actual image or fake image 
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { 
     echo "The file ". basename($_FILES["fileToUpload"]["name"]). " has been uploaded."; 
    } else { 
     echo "Sorry, there was an error uploading your file."; 
    } 
} 
add_action('edit_user_profile', 'image_up_gall'); 
add_action('show_user_profile', 'image_up_gall'); 

回答

0

你可以試試這個波紋管

if (isset($_FILES["file"]["name"])) { 

    $destination = $_POST["dir"]; 

    $name = $_FILES["file"]["name"]; 
    $tmp_name = $_FILES['file']['tmp_name']; 
    $error = $_FILES['file']['error']; 

    //echo $name; 
    //echo $tmp_name; 
    //echo $error; 

    move_uploaded_file($_FILES['file']['tmp_name'], $destination.$name); 

} 
0

首先edit_user_profileshow_user_profile行動掛鉤不必保存圖像,你可以只添加一個字段存在。所以

function image_up_gall(){ 
?> 

    Select image to upload: 
    <input type="file" name="fileToUpload" id="fileToUpload"> 
    <input type="submit" value="Upload Image" name="submit"> 
<?php 
} 
add_action('edit_user_profile', 'image_up_gall'); 
add_action('show_user_profile', 'image_up_gall'); 

這是因爲WordPress的有自己的表單標籤已經,只是確保它具有enctype="multipart/form-data"

第二步,使用personal_options_updateedit_user_profile_update可以保存表單/上傳IMAG,這樣做,使用此代碼:

function save_profile_fields($user_id) { 
$target_dir = "uploads/"; // I recommend to use wp_upload_dir() to get the correct path 
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); 
$uploadOk = 1; 
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 
// Check if image file is a actual image or fake image 
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { 
      // here the image is uploaded and we can save it to user profile with: 
      update_usermeta($user_id, 'profile_pic', $target_file); 
    } 
} 

add_action('personal_options_update', 'save_profile_fields'); 
add_action('edit_user_profile_update', 'save_profile_fields'); 

但我建議你使用WordPress默認的媒體庫要做到這一點,有大量的代碼,所以我最好給你一個鏈接到教程:https://rudrastyh.com/wordpress/customizable-media-uploader.html

+0

感謝您的幫助,但它不工作。 – Tarek

+0

你能描述一下嗎? –

+0

圖片沒有上傳。 – Tarek