Using the Media Handle Sideload Function

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.

4 responses

  1. Franco Musso Avatar
    Franco Musso

    Thanks very much for sharing this and for all the helpful code commenting! This will be a great help for a WordPress-based CRM solution I’m working on (the same goes for the many other extremely helpful tips you’ve posted but, embarrassingly, I’ve been too lazy to comment on). Ps I love your wordcamp presentations too. Keep up the great work and I hope WordPress development continues to pay dividends as your full time gig!

  2. Steffen Dressler Avatar
    Steffen Dressler

    Hey Mark,

    Thanks a lot for sharing! This recipe works great.

    Best Regards,
    Steffen

  3. Worked great, but only after I added these 3 lines:

    require_once(ABSPATH . ‘wp-admin/includes/image.php’);
    require_once(ABSPATH . ‘wp-admin/includes/file.php’);
    require_once(ABSPATH . ‘wp-admin/includes/media.php’);

Leave a Reply

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