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!

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.

Published by

Mark Wilkinson

Lead developer & owner at Highrise Digital @highrisedigital. Develops the @wpbroadbean plugins. Former teacher.

4 thoughts on “Using the Media Handle Sideload Function”

  1. 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. 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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s