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.

Bypassing WordPress Attachment Posts

This problem has been bugging me for a while now and finally I have managed to find a fix that seems to work well.  The problem being that clients, when linking to something they have uploaded to a page or post never click the ‘File URL’ for the link, instead leaving it on ‘Post URL’ which causes problems.  Here is how I fixed it.

When clients forget to click the File URL button it means that when they click on a link, instead of being show the file that they think they are linking to they are shown the post that WordPress creates for that attachment.  If the attachment is an image this not a major issue as you can include a custom image.php file in your theme folder and make that page looks nice. However if the link is to a PDF for example the user is simply presented with another post with the same link in that they just clicked on.  Worse still is that if the author has not added a title tag to the attachment they will see an ugly link.

Continue reading Bypassing WordPress Attachment Posts