Codeable info

44 Ways to Hack the WordPress Media Library

Posted on by in Blog

WordPress has evolved from a blogging tool to a fully fledged content management system (CMS). It wouldn’t run 70+ million websites if it didn’t have the capabilities that most people needed to manage content. One thing that I’ve learned over time is that while much remains the same, each website (I build) seems to have some unique requirement. Often that requirement has something to do with some type of media: audio, video, documents, images, etc.

Since I’ve been using WordPress since 2004, I can remember when it didn’t have any media management capabilities at all. There were all kinds of code snippets you could add to the “hacks” file to help manage images. Later plugins came out allowing you to upload and resize images, and then eventually media upload options were added to the WordPress core. The WordPress media library does a lot of things well, but it might not (exactly) do what you need it to do each and every time… without some tweaking.

Today we’ll go over all kinds of different ways to enhance, hack, and extend the capabilities of the WordPress media library.

Categories for the WordPress Media Library

Probably the #1 issue I have with the WordPress media library is the fact that you can’t categorize anything. I could never understand why at some point a category and / or tagging system wasn’t added specifically for media. The media library seems to have been designed with pages or posts in mind, and you once you upload something within a page or post it becomes “attached” to it. WordPress core coders seem to never have considered how you might manage groups of media.

Let me give you some website examples I’ve recently encountered with specific media requirements:

Recipe website: food images for recipes that need to be categorized by food type, meal type, and linked to their respective articles

Manfacturer website: images, and documents that need to be sorted by product line and downloadable by the end user in different variations (hi-res, lo-res, thumbnail)

Bank website: documents for accounts and loans for download, PDF files with properties and assets for sale, images of bank personel

Musician website: audio files and clips, video files and clips, images – all of which needed to be classified by event and date

Conference event website: images and documents that need to be categorized by speaker and event date

I could go on and on with examples, from realty websites, to auto dealership websites, hardware stores, carpet stores, temp agencies, artists, accountants, and more – they all have some type of media that needs to be managed.

The easiest way to solve this problem is by installing the Media Categories plugin.

As you can see in this image, the plugin allows you to create categories and sub-categories for uploaded media (the same as you would for posts):

media-categories

Then when you add an image (or other media), you can assign it to a category on upload, or when inserting it into content:

add-categories-to-media-wordpress

Once you categorize your media, you can insert it into pages and posts using the gallery shortcode.

Honorable mention to Media Library Assistant which allows categorization of media, but also allows bulk editing of many attributes, such as alt tags and metadata.

You might also check out Media Features, which allows you to organize media in categories, but it has the additional ability to adjust JPEG image quality percentages, crop and resize images, and adds support for more types of file extensions.

Adding or Importing Into the Media Library

Another pet peeve of mine when creating a new WP website has to do with importing files to the media library. If you have to add a lot of files all at once, there is no good way to do that. It can also be difficult to make bulk changes at times, especially if you want to make changes to lots of posts at once (for attachments or features images).

If you use the Upload Media by Zip plugin, you can upload a zip file and import the contents into your media library all at once. You can even attach the contents to a page or post (or not). It even adds a button to upload a zip file of media from the edit screen of pages and posts.

upload-zip-file-media-wordpress

Another plugin I like to use is Media Tools.

Here are some features at a glance:

  • ability to import external images in pages/posts to the media library
  • ability to automatically set a featured image (based on first image in the post)
  • ability to set and manage multiple thumbnail sizes
  • easily add thumbnails for your posts
  • ability to regenerate all of your thumbnails (after import)
  • allows you to convert from Timthumb conversion to built in WordPress image conversion

Basically you can think of this plugin as an “import script” for media. The image below shows the settings screen for setting featured images or importing external images. You’ll see at bottom you can choose to run it on all content, posts, pages, etc.

wordpress-media-tools

Media File Manager is another alternative for importing and/or managing media files. You can actually make sub-directories in wp-content/uploads – and move files into them (and not break any links or attachment associations).

If you were looking for more of a tagging based interface for media, you might check out WordPress Media tags, Media Tags, or WP MediaTagger.

If you’re a developer, one little known function is the media_sideload_image – which allows you to supply the URL to an image, and then download that image into the media library (and attach it to the post).

Replacing and Renaming Media Library Items

Often you have the need to rename items in the media library. Maybe it’s purely for SEO, and you need to rename dsc01234.jpg to pretty-file-name.jpg. The issue is – there’s no way to do this in WordPress, and if you rename the file in FTP the reference in the media library is lost, and you’ll break the image link in all the pages and posts it was attached to.

Enter the Rename Media plugin. It adds a simple capability, when you rename the title of a media file in the library, it automatically renames the file name of that item as well:

rename-media-wordpress

Another pain spot is the replacement of images. I can’t count the number of times I have had to update an image, and then upload and insert (the new version) to the website. If that image was on multiple pages, you have to then make the changes (to insert the new image) on all of the pages.

Wouldn’t it be easier if you could just “replace” one image (or document, or media file) with another? Enter the Enable Media Replace plugin. Once the plugin is activated, all you have to do is find the file to be replaced in the media library, and then upload the new version. That’s it!

replace-media-wordpress

Sometimes you might have to quickly change the metadata for your images (when renaming) – installing a plugin like Media Library Alt Fields allows youto edit the image alt text right from the media library screen.

Working with Media Attachments

Within WordPress you can upload media under the “Media” tab in the left sidebar, or you can “insert media” using the icon above the content editor for posts and pages. If you insert and upload media inside a post or page it gets “attached” (or associated) to that content. If you insert multiple images (or other media), you can then use the gallery shortcode to display an image gallery of all attached items. This only works for images, but you could use this hack to display PDF files and other non-image file types as well.

There is no native way to edit attachments, which is why the Unattach and Re-attach Media Attachments plugin was developed. Now you can attach media without inserting it within the edit screen of the page – you can make the changes directly from the media library screen. You can also (as the plugin implies) “unattach” and “re-attach” media files as well.

Also, another helpful thing with attachments is, you might benefit by having a meta box on the page/post edit screen that actually shows thumbnails of all the attached images (especially if there’s a lot of content). There’s a nice plugin called Gallery Metabox that gets this done.

Sometimes you can get duplicate attachments over time (not realizing you’ve uploaded the same thing multiple times). You might handle this situation with a one-off script like this one:

 
require('wp-load.php');
 
global $wpdb;
 
$img_posts = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}posts WHERE post_type like 'attachment'");
 
$img_md5s = array();
 
foreach($img_posts as $img_post){
  $single_img_md5 = md5_file($img_post->guid);
 
  if(in_array($single_img_md5, $img_md5s) && ((strpos($img_post->guid, '1.jpg')!== false) || (strpos($img_post->guid, '1.gif')!== false) || (strpos($img_post->guid, '1.png')!== false))){
    wp_delete_attachment($img_post->ID);
 
  }else{
    $img_md5s[] = $single_img_md5;
  }
}

That code will compare one image (or file) to others, and remove the duplicates.

Honorable mention to the Shuffle plugin, which allows you to attach an item to anything, re-order attachments, detach an item without deleting, or view all attachments attached to an item.

Hacking WP Media Library using functions.php

Another way to add or remove functionality to your WP media library is by adding specific code to your theme’s functions.php file.

This snippet limits non-admin and non-editor role authors ability to see all media in the library (they only see the images they uploaded):

 
add_action('pre_get_posts','users_own_attachments');
function users_own_attachments( $wp_query_obj ) {
 
    global $current_user, $pagenow;
 
    if( !is_a( $current_user, 'WP_User') )
        return;
 
    if( 'upload.php' != $pagenow )
        return;
 
    if( !current_user_can('delete_pages') )
        $wp_query_obj->set('author', $current_user->id );
 
    return;
}

This snippets adds a download link in the quick edit actions of media library items:

 
add_filter('media_row_actions', 'wpse_30159_qe_download_link', 10, 2);
 
function wpse_30159_qe_download_link($actions, $post) {
    /* Almost sure this is not necessary. Just in case... */
    global $current_screen;
    if ( 'upload' != $current_screen->id ) 
        return $actions; 
 
    // if not PDF file, return default $actions
    if ( 'application/pdf' != $post->post_mime_type )
        return $actions;
 
    // relative path/name of the file
    $the_file = str_replace(WP_CONTENT_URL, '.', $post->guid);
 
    // adding the Action to the Quick Edit row
    $actions['Download'] = 'Download';
 
    return $actions;    
}

Adding Video to the WordPress Media Library

There are several different ways you might want to add video to your WordPress media library. The first is the ability to add and externally hosted video links to the media library, and the the embed code into content.

The Add Youtube Video to Media Library plugin allows you to add a link to a Youtube video (and assign a thumbnail image for display) as a media library item. That plugin is a little basic (but it works). A more modern solution for that might be the Video Thumbnails plugin.

If you have locally hosted video uploaded to your own website, you might use the Video Embed & Thumbnail Generator plugin because it handles both the thumbnail generation, and it has a shortcode that can add a Flash / HTML5 video player with a preview image.

It uses FFMPEG, and gives you the ability to choose a thumbnail, change the embed dimensions, and video embed options – in addition to creating and encoding the multiple versions you might need within your website:

video-embed-media-library-wordpress

HTML5 Videos works great as well, but it doesn’t actually convert video. It does allow you to embed video from the media library into your posts using an HTML5 (flash fallback) player – using shortcodes.

Misc Media Library Plugins

Media File Sizes is a plugin you can install that adds a column on the media screen showing the filesize of each item.

Format Media Titles is a plugin that takes the hassle out of renaming titles on upload. It takes out the characters (like hypens, underscores, spaces) that are unnecessarily added by the media filename.

Media Filter adds width and height columns to the media library screen, as well as author link.

DownML is a plugin you can use to export, download, and backup all of the files in your WordPress media library.

Ways to Organize Media in Web Pages

The most common way to add files from the WordPress media library to webpages is by simply inserting it. Embedding images, or adding links to files for download, etc. As we mentioned before, if you attach multiple images, WordPress does have a built in “gallery” feature – and with Jetpack installed you can even create an image carousel.

One common need is the ability to display file (document) attachments within a page or post in a “pretty” way (not just a list of download links). Something like the pretty file list plugin gets the job done nicely:

pretty-file-list

Alternatively, you could use the List Attachments Shortcode plugin, and they just style the links the way you want them to look (if you require some type of unique display option).

If you need to go all out – I would recommend the File Gallery plugin which gives you a myriad of options by not only using a shortcode to display attachments, but it allows templating support as well. This can make it quite easy to control your own custom layout.

Yet another unique plugin is List Related Attachments – which (you guessed it!), shows attachments related to the ones in your current page.

There are all kinds of plugins that display images in various ways for your front end web pages. Many store the media in areas other than the WordPress media library (content folder), and store the references in their own database tables (like the very popular NextGen gallery). There are, however, solutions that work with images directly inside the default WordPress media library.

We mentioned before that WordPress has a “gallery” built-in, but maybe you want to have that display in a “carousel” (looks like a slider). You can use the jquery image carousel for WordPress plugin to get that done:

If you want something a bit more styled than the default WP gallery – you might try Polaroid Gallery. This plugin is definitely one of my favorites

The images display on the page like a pile of polaroid pics, and then open in a lightbox. Very unique and cool!

Maybe all you want to do is display an image gallery in a widget (sidebar, footer, or content area). I’ve used Really simple gallery widget a few times for this.

If you’ve found it a pain to insert (attach) a bunch of images into a page, just to use the gallery shortcode, the Gallery Buddy plugin takes the pain out of that. You can just view the images and check off the ones you want to be in the gallery, and insert the shortcode. Painless!

One feature I used to use all the time with NextGen gallery was the widget that showed the “latest images”. If / when you need to stick with the standard WordPress media library, you can use the PhotoPress latest images plugin to show the latest images uploaded (using a shortcode). If you want random instead of latest, try the WordPress Random Image plugin.

One of the first things client usually wants styled in regards to images is the addition of a “lightbox” popup to display them. This functionality isn’t native to WordPress, but if you install WP-ImageFlow2 all of your galleries will use a lightbox.

In addition to that you get a really cool scrolling gallery of styled thumbnails for display:

If you’re looking for a simpler lightbox plugin, try add-rel-lightbox.

Style My Galler is a popular plugin that adds style to your default WordPress galleries using a shortcode. You get a really cool and beautifully styled interface that you can easily add using a shortcode:

If you want to style your galleries with a strip of image thumbnails and one main image Slideshow satellite is a great solution.

I use different gallery plugins for different purposes, and recently one that caught my eye was WP-Popeye. This unique design is meant to display an “inline gallery” right in the content like this:

Another very strange (but useful) one is WP Supersized which can made a full screen slideshow background for webpages. I can’t really explain this one fully, it’s best to view the example page to see what I’m talking about.

I hope you found some new useful ways to hack the WordPress media library today. What useful tips and tricks have you come across? Please share them below in the comments.

)
Codeable info

Comments (10)

Comment by adi says:

Any idea how I can make a quick hack to get a checksum on each media item (md5sum would be enough) so that see what items are not the ones I need online and so I would update them with a correct ones.

I can’t find a plugin to do that….

Thanks,

Comment by Paolo says:

I insert images in my pages via “img-src ecc” pointing to a file in a folder on the uploads folder.
I have a doubt: it is better to insert images via “add media” from WP media library?
Thanks for the suggestion

Comment by Tom says:

Great article. Lots of helpful info. Thanks.

Comment by Matt says:

I am looking for a way to replace the src url’s for media in the media library to that of a CDN instead of locally. Do you know of any filter I can tap into or plugins that already do that?

Comment by Hugh says:

The MD5 duplicate finder code snippet was exactly what I’ve been searching for; I think you need to check your page markup tho, you’ve got HTML entity markup where you wanted symbols ( > vs > ).
cheers,
Hugh

Comment by Paul says:

Are you aware of any plugins that will clean the media library/server after using Viper’s Regenerate Thumbnails?

Meaning keep the set of the required thumbs but delete any images that do not conform to the settings in Settings>Media.

Comment by STARTUP DESIGN says:

as an agency we struggled sometimes with keeping media files organized for some websites (restaurant / design). your post will help us a lot to get a better approach – Thanks!

Comment by Frank says:

The Media Categories plugin really made magic for me. I suffered with the default Media library as it did not list if something was set Featured or was set as the Facebook OB Meta image for a post. Now I made separate categories for these with a big “do not delete” mark in the category name. Works well.

Thanks John!

Frank

Comment by Ben says:

do you know of any plugins that will assign an external mp3 as a media library item (without uploading)

similar to the ‘Add Youtube Video to Media Library’ but with external mp3s

cheers

Ben

Comment by Katie says:

Hi!! Great article. Thanks for the info.

Do you know of any plugins that allows your to re-arrange the Media Library? You may have mentioned one here, but I’m new to this whole thing and feel like I’m trying to learn a new language!! ;-) thanks so much!

Codeable info