Upload a PDF from URL

We often have to do a lot of imports from old databases / sites. This means getting images and other files and adding them to the new site’s media library and attaching them to the new post that is related to the old site’s object / page / post. With images I always used media_sideload_image and that is easy enough.

media_sideload_image example:

So that works well enough for images. However, if you want to upload any other file types, like PDFs, you need to use a different approach.

There we go! Between those 2 functions above you can upload pretty much anything with a valid URL to your media library!

NOTE: I am also using another function called url_exists(). This is a simple function that just checks to make sure there is actually something being returned from the given URL.

FINAL NOTE: Obviously I didn’t wrap most of the above code in a function but I do usually convert the above code to a function for easier use. Feel free to set that up for yourself…or not 🙂

Preview PDF

Sometimes I want to be able to show the first page / a preview of a PDF so a user knows what they are getting into. There are a variety of ways to generate an image from a PDF by running some scripts, or just saving page 1 as an image. But most of the time I do not want / have the time to run scripts on every PDF that is getting added by a client.

However, another way to do this is to just display a preview of the PDF as an object on the page. This isn’t as nice as an image in my mind, but it is still a good option. Here is the code:

Alternative text – include a link to the PDF! 

Answer stolen from StackOverflow.