WordPress ‘Attachments’ Plugin Debut

Some time ago, I began meddling around with WordPress plugins. I had a specific need that WordPress wasn’t quite up to handling out of the box, and any existing plugins were far too over the top for my taste. I’m probably a bit different than most WordPress users in that I like to get my hands dirty with plugins. I’m not a fan of shortcodes doing all the work; I’d much rather integrate the plugin data directly with my theme using good old PHP.

That said, I had an issue where I need to append any number of images to a Post. Sure, WordPress has its image gallery feature built into the editor, but I wasn’t looking for that. I didn’t want WordPress organizing and generating the content for me. It’s not that WordPress dumps out poor markup, it’s just that I was looking to build things by hand.

A number of hours later, Post Gallery emerged. According to the official WordPress Extend page, Post Gallery has been downloaded over 3,000 times. I continue to get a fair number of support requests for the plugin, and I’m really glad to have written it as it taught me quite a bit.

One of the biggest things it taught me was that it could have been written better. A lot better. So I did it, I took all of the shortcomings I saw with the plugin and completely reworked it from the ground up.

Post Gallery will officially be deprecated in favor of Attachments, a brand spankin’ new plugin that serves (in part) the same purpose.

What’s different about Attachments

As I continued to use Post Gallery on various projects, I began to wonder why the heck I decided to store the media in its own table, tucked away from the WordPress Media Library. That was the first bug under my skin. From there, technical issues with media storage snuck in by way of support emails. Then came the issue of wanting to use an image that was previously uploaded; you had to re-upload it. I was quick to decide that the rewrite would absolutely make direct use of WordPress’ Media Library. Not only does using the WordPress Media Library cut out reinventing the wheel, it allows users to recycle the same upload any number of times.

Another peeve I had with Post Gallery was the sorting I had implemented. Needless to say, you can drag and drop to reorder items in Attachments.

The official plugin home page

As of right now, I’m waiting for the WordPress team to officially add Attachments to the WordPress plugin repository. For the time being, if you’re interested in the plugin, you should first follow me on Twitter (@jchristopher) for updates, and then head over to the plugin home page as that will be home base until approval is granted.

In the meantime, if you’d like to check out a quick screencast overview of Attachments, here goes:

Suggestions more than welcome

Attachments will be my pet project for the next few months, as I’ve got a lot of ideas for handling the browse dialog. I realize that it could quickly become overwhelming with lots of media, so I’m going to begin scoping out some possible solutions. If you’ve got a use for Attachments and have any ideas for improvement, by all means let me know!

There's a conversation brewing

  1. It looks like you’ve done a great job with this plugin. Well done!

    Will it work well on a WordPress MU installation? Do you have any links that showcase interesting uses of your plugin?

    Keep on rockin.

  2. @Joe Lencioni: Great question! I actually haven’t tested on MU, but I’ve just added it to my high priority list — I’ll be sure to post my findings. My initial thought is that it’ll work fine, but better safe than sorry! No showcase sites quite yet, but a need for something like this comes up with almost every project I work on haha. Great suggestion for a section on the official plugin home page though!

  3. Hey Jonathan,

    This looks really handy – though I do have one comment (based on screen cast) – I think it would be quite handy if you could supply the media type (at least the file extension) in the attachments array.

    For example, your selection there included a bunch of files including music and photos, but without writing some kind of basic file type detection I wouldn’t be able to load any directly into the page. It’d be great to dump an assortment of media like this in on a post with no additional effort so I could handle flash movies differently to photos.

    I know I could do it myself in my own code – just grabbing the file extension using my own script – but just thought I’d suggest it as a possible option for improvement (you did ask!)

    A.

  4. @Andy: Great suggestion! I will make that change sooner than later with it being so quick. Let me ask, though: WordPress keeps track of the MIME type for each attachment, would that be more useful than the file extension? Should both be provided? What do you think?

  5. @Jonathan: Difficult, because it’s simplicity vs. complexity isn’t it? It’s probably not a bad idea to rely on internal WP detection if they already collect the MIME – it also allows the greatest flexibility for the user. Ultimately, I don’t have a strong opinion either way though, as long as I have some indication of they type of file I am working with.

    Glad you liked the idea, I’ve just got to find a use for it now!

  6. @Andy: I went ahead and just now committed version 1.0.1 and it should show up within the hour. Along with a small bug fix, the MIME type is now returned when retrieving all Attachments. That way if you’ve got GIFs, JPGs, and PNGs, you only need one conditional. It’s a double edged sword, but like you said, simplicity vs. complexity! Thanks again!

  7. Scratch that, just updated to 1.0.2

  8. Hey Jonathan.
    I found a problem in the function attachments_get_attachments in file attachments.php.

    If there are no attachment in a post, php throws a warning.
    For fixing that warning please change the function as follows:

    function attachments_get_attachments($post_id=null)
    {
    global $post;

    if($post_id==null)
    {
    $post_id = $post->ID;
    }

    $existing_attachments = unserialize(get_post_meta($post_id, ‘_attachments’, true));

    $post_attachments = array();
    if( is_array($existing_attachments) && count($existing_attachments) > 0)
    {
    if( count($existing_attachments) > 1 )
    {
    usort($existing_attachments, “cmp”);
    }
    foreach ($existing_attachments as $attachment)
    {
    array_push($post_attachments, array(
    ‘id’ => $attachment['id'],
    ‘mime’ => $attachment['mime'],
    ‘title’ => $attachment['title'],
    ‘caption’ => $attachment['caption'],
    ‘location’ => $attachment['location']
    ));
    }
    }

    return $post_attachments;
    }

  9. @Bernhard Zebedin: haha wow thanks for the bug report, and thanks so much for including the fix as well! I’ve just committed version 1.0.3 which includes the fix, you should see it show up soon!

  10. The timing on this couldn’t be better. I have to start a project this week that requires a custom image gallery and I had no idea what I’d use to pull it together. I think this is just the thing.

    Any idea if Attachments will run on a server with PHP 4 installed, or are there PHP-5-only functions in use? I’m forced to host on a bit of a legacy system in this case.

  11. @Scott Nellé: Glad it will (hopefully) help you out! Attachments should run just fine in PHP4, but if you come across any issues, feel free to post here or contact me directly and I’ll be more than happy to make sure it works for you.

  12. Your plugin is exactly what I have been looking for….except for one thing, you have to edit the core files. I’m using Thesis theme which uses the hook system., so I’ll see if there is a way around this…I’ll let you know.

  13. @Victor: Glad it might help you out! I did want to be super clear though; the plugin does not require that you edit core files, but theme files. This plugin is more-so meant for WordPress developers putting together their own themes as opposed to integrating directly with the countless themes already out there. Best of luck!

  14. Hi, this post might be a bit out of place, as it is in regards to WordPress Post Gallery (WPPG). I have been using it for 1 of my projects and am thinking to switch to WordPress Attachment (WPA) if necessary.

    I have encountered some issues with WPPG plugin and also would like to know if the WPA has fixed the issue.

    One problem is that, there are times when I edit a post with image attached to it via WPPG, I noticed the images are not loaded correctly in the Post Image panel. And when I hit update post, the image will then be gone from the post. I will then have to reattach the image.

    It may be due to bad internet connections but my client may still prefer it to be solved. Also, it happens only when I use IE8.

  15. Hi, I’m not sure if this a bug, or just a mistake made by me. But when I try to attach files I get the error “Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\wordpress\wp-content\plugins\attachments\attachments.php on line 96″ and I’m not really sure what to do about it. Any ideas?

  16. Hi Jonathan,

    Great plugin, exactly what I need! However, so far it does not work for me. I can select the pictures I like to include as an attachment in my post, but after I hit ‘Apply’ I get the following error message above the thumbnail in the attachments box:

    Warning: Invalid argument supplied for foreach() in \wp-content\plugins\attachments\attachments.php on line 96

    Also when I try to save the post it does not remember my choice.

    I test it both locally and on my webserver with same results.

    Hope you can help me fix this bug!

    Greetings,
    Andre J.

  17. @Tendouji: Very sorry to hear that Post Gallery has given you trouble. If it’s not too much of an issue I’d definitely suggest migrating to Attachments. In general, it is a much more stable and effective plugin.

    @Levi Gideon @Andre: I’ve just committed version 1.0.4 that should fix that bug, but please let me know if you continue to have problems after updating.

  18. Thanks for getting on the issue so quickly. The error message no longer shows up, but there is still an issue with the attachments not getting saved after I save the post. Thanks.

  19. Do those still having problems attaching files happen to be using any version of Internet Explorer?

  20. Hello Jonathan,

    Thanks for the quick fix. It does fix the php error message. However, I get the same result as Levi Gideon with attachments not being saved after the post/page was edited.

    Thanks for your work.

    Andre J.

  21. I’m sorry, forgot to mention this happens on Firefox 3.5.5 (mac)

  22. Hello Jonathan!

    Thank you for your plugin.
    I have installed and activated it.
    After some media items have been attached to post and the latter was saved and published nothing is saved.
    And as far as I can see attachments_get_attachments() return empty array.

    I have tested this plugin on local instance of wordpress running thru virtual host. Maybe this could be the reason thou it seems very strange.

    All files I have uploaded with attachments plugin are successfully saved wp-content/uploads directory but no items is passed to post page

    I’d be very grateful to you if recommend me something that could solve this strange issue

    best,
    Alexander

  23. The problem was caused by disabled “short open tag” in php settings of my local server

  24. @Alexander Kovalev: Ah ha! Thank you so much, I shouldn’t have let that slip under my radar but thank you. Version 1.0.4.1 has been committed which replaces shortcode echos with longcode versions.

  25. This is a very, very cool plugin! It does exactly what I need — great work! However, I’ve noticed a big problem, sorry!

    I’m using the Role Scoper plugin to manage a fairly complex permissions system for multiple users. The main users have Contributor permissions — they can only create/edit posts and have to wait for an Admin to publish them. I’ve extended their permissions with the ability to upload files — all good so far.

    Role Scoper won’t show anything in the media library that the Contributor didn’t upload which is perfect. So a Contributor can’t delete or use anything uploaded by another Contributor.

    But your plugin doesn’t respect these permissions — I can still see all the files uploaded by everyone in the media library when I use the Browse feature of the Attachments plugin. Not good.

    I guess it’s a lot of work for you, but do you think it’s possible to add integration with Role Scoper permissions?

  26. Yes, Matt Hill is right, user should only see pictures he has uploaded, not pictures uploaded by other users.
    That is also something I’m looking for.

    The only different, I’m using “Member” (http://justintadlock.com/archi.....ess-plugin) instead of Role Scoper.

  27. Thanks so much for the feedback! I’ve just committed version 1.0.5 which gives you the option to limit the available attachments to those uploaded by the current user. That should help issues with both “Member” and “Role Scoper”. Please let me know if you continue to experience any issue!

  28. Thanks for the great plugin Jonathan!
    I am running in a problem trying to move WordPress+attachments plugin from one host to another.

    The attachment data in the db table wp_postmeta (meta_key: _attachments) contains the absolute path to the attachments and now that i moved the WordPress installation to a new host the attachment URLs still refer to the old host. When i try to search/replace the old hostname with the new hostname all attachment data is lost. It’s still in the db table but it won’t show up in WordPress admin in the post attachment section. Any ideas whats going wrong here? Thanks.

  29. Looks like I’ve been looking in the wrong place. Updating the wp_posts GUID and leaving the wp_postmeta table alone worked for me – see http://www.papasoft.com/2008/1.....-database/

  30. I’m running into a trouble with captions. I have the latest version of WP running. When I add attachments, everything works fine. But as soon as I add a caption to any of the images and then update the post, all of the attachments are removed from the post. They’re still attached via the core WordPress system – so I can still add images via the Browse area – but aren’t listed in the Attachments system anymore.

  31. @Dan Philibin: Very sorry to hear that! Can I have a bit more info from you so I can troubleshoot the issue? First, have you tried deactivating all other plugins and making sure there’s no interference on that level? If so and the problem still occurs, which browser(s) have you tried it in? Thanks in advance.

  32. I have a problem in the administration page of posts (and pages too).
    After activating the plugin I see the new “Attachments” box and I see even the buttons “Browse” and “Add new”. But the browse button does not work.
    I checked the page attachment.php to see if there was a problem with the link of the button and I found this:

    Browse

    Is it normal that href is =”#”?
    Otherwise, can you help me understand why the browse button does not work?
    Thx!

    • Yes, that is in fact the proper href. Sometimes (especially if you have lots of media) it takes a moment or two for the browse modal to show up. Did you give it a few seconds and still nothing happened? What other plugins are you running on the site?

    • I have the same problem.

      Also the plugin does not seem to recognise already added attachments (images) to a post. No items are shown in the list, nor is the ‘Gallery’ tab showing when I click the plugins ‘Add’ button, it is there when I click the regular ‘Upload/insert’ link. Or are items added with the plugin kept separate from the regular media attachments?

  33. Sorry, HTML has been purged.
    What I wanted to show was this: [a href = "#" class = "button button-highlighted browse-attachments"] referred to the Browse button.

  34. I waited several minutes but unfortunately nothing happens. The site is new, just installed, and the only plugin that I’m using are cformsII and Askimet.

  35. Jonathan I love this module, but I’ve run into a problem with the ordering of attachments. I have a post with about 10 attachments. I am trying to swap a bunch of the positions, but one attachment is moved + the revert back to my orginal order when I hit update. Any ideas?

  36. Jonathan,
    I am using Attachments version 1.05
    with WordPress 2.9.1
    Let me know if you have any ideas.

  37. Great plugin. Thanks. Already extending with some front-end funcs – eg. to produce list of attachment links with media-type icons, etc. Do you happen to know if theres a list anywhere of the standard mime-type strings WP uses? (As far as I understand its based on what the server supports/returns, but info seems scarce). Cheers :)

  38. Hey… Great plugin!

    I’ve just one little question…
    Would it bee too hard to actually create an entry as an attachment?
    This way It would bee so much easyer to manage the Media Libray as you would automatically see that file “X” was attached to post “Y”.

    Cheers
    ==
    Bruno

    • I’m actually planning on integrating just that but want to stray from involving Attachments into too many WordPress core functionalities. I will definitely add your request to the pool, thank you for leaving the note!

  39. I just wondered whether your plugin, which seems from the comments to be very good, would be appropriate to be adapted for use in enabling the addition of attachments to comments? Many thanks, Stephen

  40. Hi Jonathan,

    You’ve created really great and useful plugin but there is still problem with bug reported in previous comments (comments ids: 15826, 16747, 16759).
    attachments_get_attachments function returns undefined variable when there is nothing attached to post. It should return empty array in this case.
    To fix this you should initialize $post_attachments array before those lines:
    // We can now proceed as normal, all legacy data should now be upgraded
    if( is_array( $existing_attachments ) && count( $existing_attachments ) > 0 )

    I saw in changelog that it was fixed in version 1.0.3 but there is still bug in the code in current version.
    I’m using Attachments 1.0.7.2 and WP 2.9.2

  41. Hi Jonathan,

    Fantastic plugin. Very easy to use.

    One question though, is there a way of getting the thumbnail of the first image (and first image only)?

    Say I have a loop of blog posts, and for each post I want to display a thumbnail of first attached image. (Even better if you could use location, so it just pulls the url to the thumbnail image).

    Cheers.

  42. Hi, Jonathan. Great plugin, I was searching for this for a long time.

    But I have a little problem. How can I enable Attachments screen on Custom Type Posts?

    I’m using WP3.0 beta2 with Attachments 1.0.7.2.

    Cheers

  43. Jonathan, a while back I found Post Gallery and found it very useful. Then you upgraded to Attachments and there was a simultaneous WordPress update which somehow broke Post Gallery for me and I was forced to upgrade immediately (and I lost all my photos uploaded with Post Gallery). I have since recovered many of those images.

    I have another project which still uses Post Gallery on an outdated WP install.

    Is there an easy way to migrate images from Post Gallery to Attachments? I’ve spent some time looking through FAQs and blog posts but haven’t seen anything.

    • Hey Dave, unfortunately no there is no upgrade plugin. The way the assets were stored was the primary reason for the rewrite and I have not yet written an upgrade script (hence the new plugin entirely) and at this time do not currently have plans to do so. If this is still a long standing problem, how many assets are currently in use on the other site?

  44. I’m running into problems with posts which have been saved as a draft.

    After publishing a posts which has been saved as a draft for a few days, I’ve noticed my images no longer display on my homepage, but they appear on my post page(single.php). In the “edit post area” area, the preview thumbnail disappeared as well.

    If i were to attach another image to the same post, I’d get a duplicate image in my post page but it the image would appear on my homepage.

    Any ideas why this is happening?

    • Never mind… i found the issue. My problem was caused by a similar plugin which i forgot to deactivate

  45. Hello,
    I’m looking to have aa generic images appear whenever the attachment area is left blank. How would I do that? I tried adding the following code to the Attachments code;

    <img src="/images/image-blank.jpg” alt=”" />

  46. this is what i meant to display:

    <img src="/images/image-blank.jpg” alt=”” />

  47. Hi Jonathan- awesome plugin! This is how WP should have done media from the get go. This is perfect for a site that has a clean, semantic, custom html/js gallery of photos (photography portfolio).

    However, I noticed there is no filter for assigning attachments dialog? In the normal gallery view, you can filter by month (not all that helpful really) and search.

    I think if I’m able to require prefixes for each image collection, the search could work perfectly to filter out a set of images.

    Could you maybe guide me (high level) on where / how to do that? I’m new at WP, but am a career web dev (asp.net / php) so could probably figure out quick if I had a couple clues…

    Also, do you have this plugin in source control? Github can host for free and then we can fork bug fixes and new features for you! :D

    Thanks a ton for the plugin!

    • Hi Jason – I currently have a long list of to-do’s regarding filtration and sorting for Attachments. Unfortunately the project has been a bit sluggish due to my getting married last week but with that complete I do plan on spending some newfound free time on the plugin over the next month or two. Please by all means feel free to post any additional feature requests here and I’ll do my best to integrate anything that will make the plugin that much more useful. Thanks for the feedback!

    • I wouldn’t say that’s unfortunate – congrats on the marriage!

      If it gets to be a bit much work to keep updating it, hosting on public source control (github) can be huge help. Someone can fork (branch) the code for a feature or bug fix, and then submit it to you. Then you can edit it, accept, or disregard any changes – might help get some updates with a bit less work on your side!

      Thanks for the update!

  48. This plugin is KICK ASS!!!

    Just wondering; how would I pull attachments from another post?

    For example, let’s say I have attachments on a post called “alpha,” and on post “beta,” I want to run the attachment loop, but pull in the attachments from “alpha.”

    I’m sure it’s simple, but I’m not sure how one would do that.

    • Glad you like the plugin! You can force a return of Attachments from another post by passing the ID of the Post/Page you’d like to use, e.g.

      <?php $attachments = attachments_get_attachments( 123 ); ?>

      where 123 is the Post/Page ID you’re looking to use.

  49. Sorry, one more thing (hate to be a pest).

    Is there an easy way to get attachments from multiple posts?

    Let’s assume I’m suppling the plugin with three ID’s: 2,4,6. Would I be able to use an array or something to extract the attachments from the indicated posts?

    Sorry, I’m a bit of a noob.

  50. Hi, this is definitely my favouite plugin, so simple and effective compared to vanilla wordpress gallery/attachments manager :)

    Just one question, how could i load the medium sized image (or thumbnail) instead of the original?

By all means, contribute

Leave a comment