Wordpress services, tutorials and news

WordPress upload file tutorial

How to add a file upload form to WordPress? This is the question. It’s a bit more complex, but with this tutorial you can add a browse button, save the file in the wordpress media interface and save a reference of the uploaded file in the database.

Building a form for the file upload in WordPress

Let’s create a very simple form with a text input for name and a file upload input. The most important thing regarding the form is using enctype=”multipart/form-data” – this is used when your form includes any <input type="file"> elements.

Let’s also create a simple database table using phpmyadmin to save the reference to the file upload and the title. Nothing fancy, just note that the upload_con field will save the upload id and not the actual file name:

 

Building the WordPress upload form functionality

Watch for the comments in the code. We are using the default WordPress upload functionality by including wp-load.php and the uploaded files will be available in the regular Media menu in the WordPress dashboard.  Then we define the upload folder and the file name and path, handle the possible upload file errors. If everything goes well, the file will be uploaded and we are going to create a new attachement with wp_insert_attachment.

Saving the uploaded file refence in the WordPress database

The wp_insert_attachment function will save the file metadata to the WordPress database. The output of the function is the id of the metadata, so we have defined a variable $upload_id = wp_insert_attachment that now holds the id. The next step is to save the submitted form to the database – the name and the upload_id.

To display the uploaded file somewhere else, we should retrieve the file metadata by using the upload id. For example, if it’s an image, if we know the upload_id we can show the image like this:

<?php echo wp_get_attachment_image( $image, 'small', "", array( "class" => "alignright size-small" ) ); ?>

Here is the entire code:

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Wordpress templates

responsive_wp_468x60