14/11/2020

The archive contains older posts which may no longer reflect my current views.

# In the interests of keeping everything 'front end' I've added a new toggle to my 'new post' form:

Upload Image

Clicking/tapping this reveals a new form (held in an iframe) that lets me upload a file to the WordPress media library and returns the full path so I can copy/paste straight into a post - as I've done with the screenshot above.

The original version performed the upload okay but that was it, I then had to find out how to add the proper metadata so that the image actually appeared in the library.

# Uploading a file within WordPress is actually pretty simple, you start by creating a form with the correct attribute to allow it to process files: enctype="multipart/form-data" and an input of type="file".

When the form is posted an array $_FILES is populated with all the file properties stored and access using the format $_FILES['filename']['name'] - where 'filename' is the name of the file input in the form.

To actually perform the upload you use the built in function wp_upload_bits() - here's my code:

$new_file = $_FILES['fileToUpload'];
    wp_upload_bits($new_file['name'], null, file_get_contents($new_file['tmp_name']));  

PHP saves file uploads to a temporary location (hence $new_file['tmp_name']) before moving them to their final location - in the case of WordPress that's the upload directory. The above code is all that's required to get the file in place but it will not show up in your media library because it is not referenced in the database. To fix that you use wp_update_attachment_metadata( ) and pass it the required information.

I found a great post from Misha Rudrastyh that explained exactly how to do it. I omitted a few of the checks such as mime type and size, I also don't need to check if there is no file uploaded as I have the required attribute on the file input within the form.

Misha's code performs a check to ensure the file has been properly moved from the temp location to the final location - if( move_uploaded_file(...) ) - before creating an array and adding those details to the database using wp_update_attachment_metadata( ).

Once all that is done I then display the full file path so that I can copy it into a post. The next thing I want to figure out is how to automatically place that path on the clipboard to automate things even further.

# Front end media uploads in action:

click to watch the video

2 comments: click to read or leave your own Comments