2

I'm googeling for hours now but can't find anything to my problem:

I'm building a plugin and want to embed a file input in its admin page. For this reason I'm giving the form-element the attribute enctype="multipart/form-data" and I'm trying to access the file via $_FILES, but it is empty! Same with $_POST.

Without enctype="multipart/form-data" at least the filename and the other form fields appear in $_POST.

I'm wondering if WordPress is removing direct access to these superglobals or somehow else preventing this regular way of uploading files.

I've read a lot about hooks and posting all forms to admin_post.php or admin_ajax.php but since my upload functionality is located in a class that's part of a big library with autoloading etc. it's not an option for me. My form is sending it's data to the current admin page (I tried it without the action-Attribute but also specifying it action="admin.php?page=XYZ" but nothing worked).

I would be thankful for every hint!

0

If you want to upload in a custom folder you can use the following function. Add the function in functions.php

function upload_user_file( $file = array(),$path ) {
    if(!empty($file)) 
    {


        $upload_dir=$path;
        $uploaded=move_uploaded_file($file['tmp_name'], $upload_dir.$file['name']);
        if($uploaded) 
        {
            echo "uploaded successfully ";

        }else
        {
            echo "some error in upload " ;print_r($file['error']);  
        }
    }

}

Make a form in your template file like this:

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" name="upload">
</form>

Call the upload function in template file like before get_header() function:

if(isset($_POST['upload']))
    {

       if( ! empty( $_FILES ) ) 
       {
          $file=$_FILES['file'];   // file array
          $upload_dir=wp_upload_dir();
          $path=$upload_dir['basedir'].'/myuploads/';  //upload dir.
          if(!is_dir($path)) { mkdir($path); }
          $attachment_id = upload_user_file( $file ,$path);

       }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.