WordPress is equipped with lots of great functions that you probably haven’t heard of and recently I came across a couple of little gems whilst working on a project. He is how I used the media_handle_sideload
function in a project.
The project in question was an integration of Broadbean with the WP Job Manager WordPress plugin. In fact the work I have done will soon to be a service offered on their add-ons page along with the LogicMelon add-on service I already have on there.
I needed to be able to take a URL which was being sent to the WordPress site which was a PDF, Word document or an image and have WordPress add this file to the media library so that I could link to it on the WordPress site.
Having done some investigation I came across the media_handle_sideload
function which effectively does just that. It will take a URL, and attach it to a post.
Below is the code I have used to grab a file from a URL and attach it to a post. It is well commented in order to help understand what is going on!
https://gist.github.com/wpmark/15e3dd1b9e6f81b83904
It is a really handy function and one I am sure I will use more with plugins and code that require that or a similar functionality.
Leave a Reply