WordPress 3.6 introduced the new get_attached_media() function that makes it really simple to retrieve all media attached to a specific post.
Previously, if you wanted to retrieve the items attached to a post, you’d do something like this:
1 2 3 4 5 6 7 8 9 10
$args = array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'posts_per_page' => -1, 'orderby' => 'menu_order', 'order' => 'ASC', ); $attachments = get_children( $args );
This is pretty straight forward, but WordPress 3.6 makes it even easier by letting us use the get_attached_media() function.
Retrieve all attached media, regardless of mimetype:
$attachments = get_attached_media( '', $post->ID );
Retrieve all attached audio files:
$attachments = get_attached_media( 'audio', $post->ID );
Retrieve all attached images:
$attachments = get_attached_media( 'image', $post->ID );
Retrieve all attached videos:
$attachments = get_attached_media( 'video', $post->ID );
11 thoughts so far
Have your say
That replaces one of my oldest snippets of code, makes development a little cleaner too! is that last parameter right for video? mimetype image?
Whoops. Fixed. It was supposed to be “video”.
It’s a great addition. Unfortunately, we’ll still need to wait for people to upgrade before deploying it across all plugins.
You could do something like this in your plugins:
Nice. I’m wondering how to go about using this function to query for and display attachments within a particular custom taxonomy (associated with attachments). Any ideas?!
Can you elaborate a little more?
Cool. Let say we have a custom taxonomy ‘attachment-cats’ that is associated to attachments. Each tax term is something like cars, boats, planes, buildings etc etc. I have 2 possible desired outcomes. 1 show separate taxonomy based galleries on a single post page using attached images/media without having to insert gallery. 2 show show a list of posts that instead of using ‘featured image’ they would use an attached image within a particular taxonomy. I know there are work arounds to above but I’m trying to avoid using custom fields for certain things. Make any more sense?
So pulling images from the posts that are filed in specific terms?
No, pulling the attachments themselves that are filed in custom tax terms and outputting them separately according to their term (for instance in separate tabs – as opposed to just showing every attachment). Taxonomy meta box can be added to the ‘edit attachment’ screen. I’ll take a stab at it – thought it might have been done already
Similar to this but for attachments? http://codecanyon.net/item/posts-by-taxonomy-widget-pro/459856
hi, is there a way to reorder images without creating and inserting a gallery?
Comments are closed.
Leave a reply
Join the discussion