I’ve just spent a bit of time wrangling with the issue of how to utilize the WordPress Media Library for custom fields. That is, if I have a custom post meta box (I’m using my custom fields plugin for this) into which I want people to put an image or a file, how can I get the popup overlay to work for me?
Thanks to some code in the excellent new book Professional WordPress Plugin Development, I got on the right track. However, this code only dealt with images, and it inserted the URL of the image into the custom field. I wanted more flexibility. I wanted the ID of the file attachment, plus the ability to deal with files of all types, not just images.
The result—so far—is this plugin:
Install as per any other plugin, and use it by calling this function:
slt_fs_button( $name, $value [, $label, $preview_size, $removable ] );
$name is the name / ID for the field;
$value is the current value;
$label is a label for the button that’s pressed to open the overlay;
$preview_size is the image size to be used for the preview;
$removable signals whether to include a checkbox to remove the selected file. Check the code itself for more details.
The above function will output:
- A button to open the Media Library
- An optional checkbox for file removal
- A hidden field to hold the actual file ID when selected
- A preview of the selected image, or a link to the non-image file
I’ve included a few icons for common file types.
The plugin also disables the “From URL” tab when it opens the overlay. Because it relies on grabbing an image ID, I didn’t see a use for this aspect.
Obviously there’s a lot of scope for improvement, and there’ll certainly be a few bugs to iron out. But hopefully this’ll prove useful for plugin and theme developers.
People who are using my Custom Fields plugin, please note that I’ve not updated the version here on this site to use this plugin yet. This functionality will be included in the imminent new version (which will require File Select for file upload fields).
Please let me know your thoughts and experiences!