Obmerk Kronen
Obmerk Kronen

Reputation: 15979

wordpress get attachments that are not images

wordpress has really great functions when it comes to image attachments - but I can not find any documentation on how to get attachments that are not images .

for now, I wrote this function :

function ok99_get_post_file_attachment($mime='application/pdf',$limit=-1) {
    global $post;
    $attachments = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment','post_mime_type' => $mime, 'order' => 'ASC', 'orderby' => 'menu_order ID', 'posts_per_page'=>$limit) );

    if ($attachments) {
       echo 'Your Attachments : <br/>';
        foreach ($attachments as $att) {
        //$attachment = array_shift($attachments); // debug to delete
        echo wp_get_attachment_url($att->ID) . '<br/>';
        the_attachment_link($attachment->ID, false);}
    }

    return false;
}

my question is : is this the only way to get attachments that are not images ? Is there any way to do that without another query ??

Upvotes: 1

Views: 1638

Answers (3)

Simon
Simon

Reputation: 3727

I'm using this technique for querying attachments that are not images or video files, i.e. a "negative" mime type query. It returns an array of post objects (similar to what would be returned by get_posts(), and could easily be modified to exclude other types of attachment media, or made completely generic using vsprintf().

function wpse9927425_get_downloads($post_id) {
    global $wpdb;

    $sql_query = $wpdb->prepare(
        "SELECT * FROM $wpdb->posts
        WHERE post_type = %s
            AND post_parent = %d
            AND post_mime_type NOT LIKE %s
            AND post_mime_type NOT LIKE %s
        ORDER BY menu_order, post_title ASC",
        'attachment',
        $post_id,
        'image/%',
        'video/%'
    );
    $files = $wpdb->get_results( $sql_query );

    return $files;
}

Upvotes: 3

rezon8dev
rezon8dev

Reputation: 1

I am getting non-image attachments by specifying the MIME type like so:

if ( $attachments = get_children( array(
    'post_type' => 'attachment',
    'post_mime_type' => array('application/doc','application/pdf', 'text/plain'),
    'numberposts' => 15,

)));
foreach ($attachments as $attachment) {
echo '<a href="' . wp_get_attachment_url( $attachment->ID ) . '">Download Fact    Sheet</a>';
echo '</div>';
}

Upvotes: 0

Obmerk Kronen
Obmerk Kronen

Reputation: 15979

It seems that Once again I will need to answer myself - also because I got no other input for this question

there appears to be no other way of doing that (meaning - there are a lot of ways - but not without another direct query)

Upvotes: 0

Related Questions