brasofilo

Grab one attachment of a given kind

Oct 6th, 2011
179
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. /*
  3.  * WordPress Function
  4.  * Drop in your functions.php, or create a simple plugin (and drop all your functions there)
  5.  * Parameter $idi : the $post-ID
  6.  * Parameter $type : A full or partial mime-type, e.g. image, video, video/mp4, application/pdf
  7.  * Usage : <a href="<?php echo getAttach($post->ID,'video'); ?>">download video</a>
  8.  */
  9.  
  10. function getAttach($idi,$type)
  11. {
  12.     $empty = "no attach...";
  13.     if ( $files = get_children(array(   //do only if there are attachments
  14.      'post_parent' => $idi,
  15.      'post_type' => 'attachment',
  16.      'numberposts' => 1,
  17.      'post_mime_type' => $type,  
  18.      'order' => 'ASC',
  19.      'orderby' => 'menu_order'
  20.      ))){
  21.          foreach( $files as $file ){ // only run once, as numberposts = 1
  22.             $file_link = wp_get_attachment_url($file->ID);    //get the url for linkage
  23.           }
  24.           return $file_link;
  25.     }
  26.     else
  27.     {
  28.         return $empty;
  29.     }
  30. }
  31. ?>
RAW Paste Data