0

I'm creating an online area for our staff to create new posts in WordPress to share lesson resources with students. I'm currently developing a section whereby students are able to upload documents to the custom post (front end form) and these uploads are then stored in the Uploads directory.

Currently, I've got it to upload to the directory but I can't work out how to create a new folder based on what the Post ID is.

Any ideas greatly appreciated.

include_once plugin_dir_path( __FILE__ ).'upload.php';

function assignment_uploads(){

  global $post;

  echo '
    <form method="post" enctype="multipart/form-data" action="">
        <input type="file" name="file_upload">
        <input type="hidden" name="lesson_id" value="'. $post->ID.'">
        <input type="submit" name="upload_submitted">
    </form>
  ';
}
add_shortcode( 'student_submission_upload_form', 'assignment_uploads' );

// store post id in var
$lesson_id = $_POST['lesson_id']; 

function create_uploads_folder() {
    $upload_dir = $uploadFolder['basedir'];
    $upload_dir = $upload_dir . '/submissions/'.$lesson_id;
    if (! is_dir($upload_dir)) {
       mkdir( $upload_dir, 0705 );
    }
}
register_activation_hook( __FILE__, 'create_uploads_folder' );

// Upload file
if(!move_uploaded_file($_FILES['file_upload']['tmp_name'], $uploadFolder['basedir'] . '/submissions/' . $lesson_id . '/' . $_FILES['file_upload']['name'])){
    die('Error uploading file - check destination is writeable');
}

1 Answer 1

0

I wrote this code for you:

global $lesson_id;
$lesson_id = $_POST['lesson_id']; 

function create_uploads_folder() {
    global $lesson_id;

    $upload_dir = wp_upload_dir();
    $upload_dir = $upload_dir['basedir'];
    $upload_dir = $upload_dir . '/submissions/'. $lesson_id;
    if ( ! is_dir( $upload_dir ) ) {
        wp_mkdir_p( $upload_dir );
    }
}

register_activation_hook( __FILE__, 'create_uploads_folder' );

// Upload file
$uploadFolder = wp_upload_dir();
if ( ! move_uploaded_file($_FILES['file_upload']['tmp_name'], $uploadFolder['basedir'] . '/submissions/' . $lesson_id . '/' . $_FILES['file_upload']['name'])){
    die('Error uploading file - check destination is writeable');
}
6
  • Hi. Code doesn't work. It still doesn't create the directory. Jun 28, 2017 at 10:14
  • Try the above code again Jun 28, 2017 at 10:28
  • Try active your plugin deactivate and then on again. Jun 28, 2017 at 10:30
  • Still no luck! move_uploaded_file(/submissions/37/Student Feedback.docx): failed to open stream: No such file or directory Jun 28, 2017 at 12:02
  • Creating the folder? Jun 28, 2017 at 12:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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