How does one grab an attachment ID of file types that are not images?

I’ve found a terrific number of tutorials/code examples which provide you with the code to grab and echo the attachment ID of an image, but not a single one which works with anything else, such as Zip and Rar archives – which is precisely what I’ve working with.

Would anyone know how to go about grabbing and echoing the ID of a file (in this case, a Zip archive) from within WordPress attachment.php page? Oddly enough, grabbing the ID of a Zip archive appears simple when attempted via single.php, but I’m really struggling to nail this from within attachment.php.

Read More

Really can’t understand why WordPress has a built-in get_post_thumbnail_id(); for images, but nothing available for any other type of file.

Related posts

Leave a Reply

2 comments

  1. Refer to the example Show All attachments for the current post beside Thumb on (ironically, given your comments!) the get_post_thumbnail_id() codex page.

    Basically you set up a get_posts() query for all attachments. You’d then just need to filter your results on file type extension, or if you know it (and it’s recorded correctly), the WP_Post.post_mime_type using get_post_mime_type().

    (The example filters out the featured image/thumb too… But your filter would take care of that anyhow).

    But if you can use the MIME type as a filter, you can set up the get_posts() args with a 'post_mime_types' argument, to only return attachments of one (or more) specific MIME type(s). You’d probably want to take a peek at the attachments’ underlying database entries to check how this is recorded so that you can properly match against it. I expect your .zip files are application/zip, but I’d double check before relying on that.

    So, something like:

    <?php
    
    $args = array(
        'post_type'   => 'attachment',
        'numberposts' => -1,
        'post_status' => null,
        'post_parent' => $post->ID,
        'post_mime_type' => 'application/zip'
        );
    
    $attachments = get_posts( $args );
    
    ?>
    
  2. Thanks for responding, Sepster. I managed to find the embarrassingly simple answer by scouring through one of the TwentyTwelve theme’s files; turns out the answer is as simple as echoing…

    <?php the_ID(); ?>
    

    …inside the attachment.php file.