WordPress Attachments – Part 1

A powerful tool that is vastly underused, attachments in WordPress offer many opportunities for great plug-ins. For example, many complain about WordPress lacking a good integrated image gallery. Various solutions exist (e.g., zen photo, gallery, etc.), however none of them offer deep integration into WordPress. The way WordPress deals with attachments changed greatly in 2.0, and since then, the attachment API has gone mostly undocumented, a real bummer for plug-in developers.

“No API documentation, how am I supposed to use them then?”

Fear not, however, Michael Adams, in his blog listed the available API functions for attachments last December.

“But wait, that was almost a year ago, and that was WordPress 2.0, we’re at 2.3 now.”

Don’t worry I’ve tested the functions he offered and I’m going to do some documentation in this post and an few others. Let’s start with the list of functions that still exist in the attachment API for WordPress 2.3.

  • get_attachment_icon([$ID])
  • wp_get_attachment_url([$ID])
  • wp_attachment_is_image([$ID])
  • wp_mime_type_icon()
  • wp_get_attachment_metadata()
  • wp_update_attachment_metadata()
  • get_attached_file()
  • update_attached_file()

string get_attachment_icon([$ID]) returns code for the attachment’s thumbnail (if applicable). The id of the attachment may be specified, if it is not the current (page/post/attachment) id will be used.

string wp_get_attachment_url([$ID]) returns the URL to the attachment (the file not page). Again the id of the attachment may be specified, otherwise it defaults to the current (page/post/attachment) id.

bool wp_attachment_is_image([$ID]) returns true if the attachment is an image, or false if not. Once again the id of the attachment may be specified, otherwise the function defaults to the current (page/post/attachment) id.

Note that I document functions including their return type, this is because it is useful when some functions echo out data instead of returning it. This is only part one, time permitting, next week part two will be released with an investigation into the next tree API functions on the list. I am currently working on a project that will be making extensive use of attachments, and will keep exploring them as work on the project progresses. Additionally look for a simple WordPress attachment based gallery system appearing in the future (around the time WordPress 2.4 is released since a bugfix in WordPress is necessary for some permalink structures).

-John Havlik

[end of transmission, stay tuned]