Upload a file in wordpress with custom form using move_uploaded_file() function.
Uploading a file in wordpress
/*Make a form*/
<form method=”post” enctype=”multipart/form-data” action=””>
<div class=”form-group”>
<label for=”title”>Title</label>
<input type=”text” class=”form-control” name=”title”>
</div>
<div class=”form-group”>
<label for=”File”>Select file</label>
<input type=”file” class=”form-control-file” name=”gfile”>
</div>
<button class=”btn btn-primary” type=”submit” name=”formsubmit”>Submit</button>
</form>
/*Check the form has been submitted*/
<?php
if(isset($_POST[‘formsubmit’]))
{
global $wpdb;
$table_name = $wpdb->prefix.’my_gallery’;
$data[‘title’] = $_POST[‘title’];
$tmpFilePath = $_FILES[‘gfile’][‘tmp_name’];
if($tmpFilePath != “”)
{
$upload_url = wp_upload_dir(‘url’);
$filePath = $upload_url[‘path’] . date(‘d-m-Y-H-i-s’).’-‘.$_FILES[‘gfile’][‘name’];
$fileurl = $upload_url[‘url’] . date(‘d-m-Y-H-i-s’).’-‘.$_FILES[‘gfile’][‘name’];
if(move_uploaded_file($_FILES[‘gfile’][‘tmp_name’], $filePath))
{
$data[‘image’] = $fileurl;
$success=$wpdb->insert($table_name, $data);
if($success)
{
$messages= “<div class=’alert alert-success’><h5 style=’color:#2e2a2a;padding: 17px 0px 0px 16px; letter-spacing:0px;’>Gallery Added Successfully.</h5></div>”;
}
else{
$messages= “<div class=’alert alert-danger’><h5 style=’color:#2e2a2a;padding: 17px 0px 0px 16px;’>Please try again.</h5></div>”;
}
}
}
else
{
$messages= “<div class=’alert alert-danger’><h5 style=’color:#2e2a2a;padding: 17px 0px 0px 16px;’>Please try again.</h5></div>”;
}
}
?>