I’m trying to make an assignment uploader for WordPress, and I want users that are logged in to be able to submit data through a form on the front-end and have it create a post in the back-end. I’ve been able to create a shortcode function that allows an admin to choose where they want this form to appear, and when the form submits, it does create a post in the back-end. The problem is, I want the logged in user to be able to attach a file to the post as well, so that the admin can download the file from the back-end.
Here is the shortcode for the form:
add_shortcode('assignmentForm','wprmAssignmentForm');
function wprmAssignmentForm() {
if (is_user_logged_in()){ ?>
<form id="custom-post-type" name="custom-post-type" method="post" action="">
<p>
<label for="title">Assignment Title</label><br />
<input type="text" id="title" value="" tabindex="1" size="20" name="title" />
</p>
<p>
<label for="description">Assignment Content</label><br />
<?php //wp_editor( '', 'description', array( 'media_buttons' => false, 'textarea_rows'=>5 ) ); ?>
<textarea id="description" tabindex="3" name="description" cols="50" rows="6"></textarea>
</p>
<p>
<label for="upload">Upload File</label><br />
<input type="file" name="upload" id="upload">
</p>
<p align="right"><input type="submit" value="Publish" tabindex="6" id="submit" name="submit" /></p>
<input type="hidden" name="post-type" id="post-type" value="custom_posts" />
<input type="hidden" name="action" value="custom_posts" />
<?php wp_nonce_field( 'name_of_my_action','name_of_nonce_field' ); ?>
</form>
<?php
if($_POST){
wprmSaveSubmission();
}
}
else {
echo '<p>You must be logged in to submit an assignment!</p>';
}
}
And here is the saving function:
function wprmSaveSubmission() {
if ( empty($_POST) || !wp_verify_nonce($_POST['name_of_nonce_field'],'name_of_my_action') ) {
exit;
}
else {
// Basic validation
if (isset ($_POST['title'])) {
$title = $_POST['title'];
}
else {
echo 'Please enter a title';
exit;
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
}
else {
echo 'Please enter the content';
exit;
}
// Add the content of the form to $post as an array
$post = array(
'post_title' => wp_strip_all_tags( $title ),
'post_content' => $description,
'post_status' => 'publish',
'post_type' => 'wprm-assignments'
);
wp_insert_post($post);
}
}
I have the file uploader field in the form, but I don’t know how I can have the upload saved somewhere and then be offered as a download with the post in the backend. Any ideas on how I could achieve this?
WordPress Provides its predefined functions to upload media to the site. Using these functions in your custom code you can upload any file which wordpress supports into media as an attachments.
Here is the link which can help you with with further details on how to use those functions in your code.
Try this and let me know if that resolves your issue.