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 🙂

WordPress Static Variables

Sometimes I want to setup some variables to be used across various scripts and I don’t want to have to pollute the global variables. We setup some functionality in house for creating variables we can use throughout our scripts in a site.

Now you can set and get any variable you want throughout your scripts.

Array Splice Associative

Sometimes I want to put an array into another array at a certain position. array_splice works for regular arrays, but does not keep the keys. Here is a function that will work like array splice, BUT it will maintain the keys.

 

Attach a Server File to a Post

Like the last post, sometimes what we want isn’t to attach an uploaded file, but perhaps some setup files or other default image files that we know will need to get setup on a page. Here is a function for that.

Now all we need to do to attach this image is call the function like so:

 

Attach an uploaded file

Sometimes when spinning up a new site, especially a multi-site, you need to make sure to populate some attachments. Here is a function to make this easier.

If you want to do this for a single file upload you can call this function like so:

If you want to use this to upload multiple files in an upload:

 

PHP Calculate Distance

A while ago I had a project I needed to query multiple locations to calculate the distance between that location and another. Here is a script which will get you started with that task.