Automate File Attachments on your WordPress Posts

January 16th, 2010 by Tony | Print

UPDATE 4/24/2010: I updated the audio section to automatically wrap the audio with the flash player based on the example provided by Joseph Hinson

I’ve been coding WordPress sites for 4 or 5 years now. The more I use it, the more I love it. WordPress is an awesome CMS tool. When I create a site for a client, I want the site to be as easy as possible for a “non” web designer/developer types to maintain. One of my latest clients wanted to be able to create a post and attach a file for download. The client found it a little confusing to attach the file to a post and then include that file as a link. They also wanted to show an icon specific to the document type they had uploaded. With a little code, I was able to automate the process of linking to files attached to a WordPress post and specify the icon based on the files MIME type. There are plenty of articles on the web about WordPress attachments so I’m not going into any detail about that. Here is an article on attachments by Jeff Starr I’ve bookmarked for reference. Digging into WordPress

Here is an example of what we are about to create. I’ve attached several sample files to this post and that’s it. By the way, the zip file listed below is a zip of all the icons for you to download.

  • Jeopardy Think Music

    Download

    First let’s create the function and the shortcode. Go to your themes folder and open functions.php. If you don’t have one, just create a new file named functions.php and save it to your themes folder.

    Create a new function with the following code.

    function get_attachment_icons($echo = false){
    	//PDF Documents
    	if ( $files = get_children(array(   //do only if there are attachments of these qualifications
    	 'post_parent' => get_the_ID(),
    	 'post_type' => 'attachment',
    	 'numberposts' => -1,
    	 'post_mime_type' => 'application/pdf',  //MIME Type condition
    	 ))){
    	 foreach( $files as $file ){ //setup array for more than one file attachment
    		$file_link = wp_get_attachment_url($file->ID);    //get the url for linkage
    		$file_name_array=explode("/",$file_link);
    		$file_name=array_reverse($file_name_array);  //creates an array out of the url and grabs the filename
    		$sAttachmentString .= "<div class='documentIcons'>";
    		$sAttachmentString .= "<a href='$file_link'>";
    		$sAttachmentString .= "<img src='".get_bloginfo('template_directory')."/images/mime/pdf.png'/>";
    		$sAttachmentString .= "</a>";
    		$sAttachmentString .= "<br>";
    		$sAttachmentString .= "<a href='$file_link'>$file_name[0]</a>";
    		$sAttachmentString .= "</div>";
    		}
    	}
    

    This block is for PDF files. You can tell that by the line that says ‘post_mime_type’ => ‘application/pdf’,. Just change the MIME type for the type of file you are expecting. In the final code, I’ve added a new loop for each MIME type below:

    • PDF = application/pdf
    • Word Documents = application/msword
    • PowerPoint = application/vnd.ms-powerpoint
    • Excel = application/vnd.ms-excel
    • Zip = application/zip
    • Audio files = audio/mpeg

    Now at the bottom of the function we will add the hook for the shortcode and we’re done!

    add_shortcode('attachment icons', 'get_attachment_icons');

    Usage

    Just include a shortcode in any post

    [attachment icons]

    or place one line in your single.php file (or where ever you’d like the document icons to show up)

    <?php get_attachment_icons($echo=true); ?>

    Final Code

    Here is the code altogether for your copying and pasting pleasure. Enjoy!

    function get_attachment_icons($echo = false){
    	$sAttachmentString = "<div class='documentIconsWrapper'> \n";
    	if ( $files = get_children(array(   //do only if there are attachments of these qualifications
    	 'post_parent' => get_the_ID(),
    	 'post_type' => 'attachment',
    	 'numberposts' => -1,
    	 'post_mime_type' => 'application/pdf',  //MIME Type condition
    	 ))){
    	 foreach( $files as $file ){ //setup array for more than one file attachment
    		$file_link = wp_get_attachment_url($file->ID);    //get the url for linkage
    		$file_name_array=explode("/",$file_link);
    		$file_name=array_reverse($file_name_array);  //creates an array out of the url and grabs the filename
    		$sAttachmentString .= "<div class='documentIcons'>";
    		$sAttachmentString .= "<a href='$file_link'>";
    		$sAttachmentString .= "<img src='".get_bloginfo('template_directory')."/images/mime/pdf.png'/>";
    		$sAttachmentString .= "</a>";
    		$sAttachmentString .= "<br>";
    		$sAttachmentString .= "<a href='$file_link'>$file_name[0]</a>";
    		$sAttachmentString .= "</div>";
    		}
    	}
    	//Word Documents
    	if ( $files = get_children(array(   //do only if there are attachments of these qualifications
    	 'post_parent' => get_the_ID(),
    	 'post_type' => 'attachment',
    	 'numberposts' => -1,
    	 'post_mime_type' => 'application/msword',  //MIME Type condition
    	 ))){
    	 foreach( $files as $file ){ //setup array for more than one file attachment
    		$file_link = wp_get_attachment_url($file->ID);    //get the url for linkage
    		$file_name_array=explode("/",$file_link);
    		$file_name=array_reverse($file_name_array);  //creates an array out of the url and grabs the filename
    		$sAttachmentString .= "<div class='documentIcons'>";
    		$sAttachmentString .= "<a href='$file_link'>";
    		$sAttachmentString .= "<img src='".get_bloginfo('template_directory')."/images/mime/word.png'/>";
    		$sAttachmentString .= "</a>";
    		$sAttachmentString .= "<br>";
    		$sAttachmentString .= "<a href='$file_link'>$file_name[0]</a>";
    		$sAttachmentString .= "</div>";
    		}
    	}
    	//Powerpoint Documents
    	if ( $files = get_children(array(   //do only if there are attachments of these qualifications
    	 'post_parent' => get_the_ID(),
    	 'post_type' => 'attachment',
    	 'numberposts' => -1,
    	 'post_mime_type' => 'application/vnd.ms-powerpoint',  //MIME Type condition
    	 ))){
    	 foreach( $files as $file ){ //setup array for more than one file attachment
    		$file_link = wp_get_attachment_url($file->ID);    //get the url for linkage
    		$file_name_array=explode("/",$file_link);
    		$file_name=array_reverse($file_name_array);  //creates an array out of the url and grabs the filename
    		$sAttachmentString .= "<div class='documentIcons'>";
    		$sAttachmentString .= "<a href='$file_link'>";
    		$sAttachmentString .= "<img src='".get_bloginfo('template_directory')."/images/mime/PowerPoint.png'/>";
    		$sAttachmentString .= "</a>";
    		$sAttachmentString .= "<br>";
    		$sAttachmentString .= "<a href='$file_link'>$file_name[0]</a>";
    		$sAttachmentString .= "</div>";
    		}
    	}
    	//Excel Documents
    	if ( $files = get_children(array(   //do only if there are attachments of these qualifications
    	 'post_parent' => get_the_ID(),
    	 'post_type' => 'attachment',
    	 'numberposts' => -1,
    	 'post_mime_type' => 'application/vnd.ms-excel',  //MIME Type condition
    	 ))){
    	 foreach( $files as $file ){ //setup array for more than one file attachment
    		$file_link = wp_get_attachment_url($file->ID);    //get the url for linkage
    		$file_name_array=explode("/",$file_link);
    		$file_name=array_reverse($file_name_array);  //creates an array out of the url and grabs the filename
    		$sAttachmentString .= "<div class='documentIcons'>";
    		$sAttachmentString .= "<a href='$file_link'>";
    		$sAttachmentString .= "<img src='".get_bloginfo('template_directory')."/images/mime/XLS8.png'/>";
    		$sAttachmentString .= "</a>";
    		$sAttachmentString .= "<br>";
    		$sAttachmentString .= "<a href='$file_link'>$file_name[0]</a>";
    		$sAttachmentString .= "</div>";
    		}
    	}
    	//Zipped Files
    	if ( $files = get_children(array(   //do only if there are attachments of these qualifications
    	 'post_parent' => get_the_ID(),
    	 'post_type' => 'attachment',
    	 'numberposts' => -1,
    	 'post_mime_type' => 'application/zip',  //MIME Type condition
    	 ))){
    	 foreach( $files as $file ){ //setup array for more than one file attachment
    		$file_link = wp_get_attachment_url($file->ID);    //get the url for linkage
    		$file_name_array=explode("/",$file_link);
    		$file_name=array_reverse($file_name_array);  //creates an array out of the url and grabs the filename
    		$sAttachmentString .= "<div class='documentIcons'>";
    		$sAttachmentString .= "<a href='$file_link'>";
    		$sAttachmentString .= "<img src='".get_bloginfo('template_directory')."/images/mime/zip.png'/>";
    		$sAttachmentString .= "</a>";
    		$sAttachmentString .= "<br>";
    		$sAttachmentString .= "<a href='$file_link'>$file_name[0]</a>";
    		$sAttachmentString .= "</div>";
    		}
    	}
    
    	//Audio Files
    	$mp3s = get_children(array(   //do only if there are attachments of these qualifications
    	 'post_parent' => get_the_ID(),
    	 'post_type' => 'attachment',
    	 'numberposts' => -1,
    	 'post_mime_type' => 'audio',  //MIME Type condition
    	 ) );
    
    	if (!empty($mp3s)) :
    	$sAttachmentString .= "<ul class='audiofiles'>";
    		foreach($mp3s as $mp3) :
        		$sAttachmentString .= "<li>";
    			if(!empty($mp3->post_title)) : //checking to make sure the post title isn't empty
    				$sAttachmentString .= "<h4 class='title'>".$mp3->post_title."</h4>";
    			endif;
    
    			if(!empty($mp3->post_content)) : //checking to make sure something exists in post_content (description)
    				$sAttachmentString .= "<p class='description'>".$mp3->post_content."</p>";
    			endif;
    
    			$sAttachmentString .= "<object width='470' height='24' id='single".$mp3->ID."' name='single".$mp3->ID."'>";
    				$sAttachmentString .= "<param name='movie' value='player.swf'>";
    				$sAttachmentString .= "<param name='allowfullscreen' value='true'>";
    				$sAttachmentString .= "<param name='allowscriptaccess' value='always'>";
    				$sAttachmentString .= "<param name='wmode' value='transparent'>";
    				$sAttachmentString .= "<param name='flashvars' value='file=".$mp3->guid."'>";
    					$sAttachmentString .= "<embed ";
    					  $sAttachmentString .= "id='single".$mp3->ID."' ";
    					  $sAttachmentString .= "name='single".$mp3->ID."' ";
    					  $sAttachmentString .= "src='".get_bloginfo('template_directory')."/jw/player.swf' ";
    					  $sAttachmentString .= "width='470' ";
    					  $sAttachmentString .= "height='24' ";
    					  $sAttachmentString .= "bgcolor='#ffffff' ";
    					  $sAttachmentString .= "allowscriptaccess='always' ";
    					  $sAttachmentString .= "allowfullscreen='true' ";
    					  $sAttachmentString .= "flashvars='file=".$mp3->guid."' ";
    
    					$sAttachmentString .= "/>";
    			$sAttachmentString .= "</object>";
                            $sAttachmentString .= "<a href='".$mp3->guid."'>Download</a>";
    			$sAttachmentString .= "</li>";
    		endforeach;
    	$sAttachmentString .= "</ul>";
    	endif;
    $sAttachmentString .= "</div>";
    if($echo){
        echo $sAttachmentString;
      }
      return $sAttachmentString;
    }
    add_shortcode('attachment icons', 'get_attachment_icons');

    17 Responses to “Automate File Attachments on your WordPress Posts”

    1. Erik says:

      This is really great! Thanks for the post.

    2. Ignacio says:

      This is really helpfull THANKS

    3. Manny says:

      Where do you place the icons in the directory?

      • Tony says:

        In my example the icons are in my theme folder at /images/mime/

        < img src='".get_bloginfo('template_directory')."/images/mime/pdf.png'/ >

        Here is the line that tells you where the icons are located but you can change this and put them anywhere you want.

        • Manny says:

          Thanks Tony got the image taken care of. Now, I’ve tried inserting the into the single.php but it not working. However, inserting the [attachment icons] into a post works.

          Any suggestions how to or where to put the This would make it easier than for end-user to keep remembering to insert the shorter code.

          thanks in advance!

          • Tony says:

            The call has to be inside the loop

            < ?php if (have_posts()) : while (have_posts()) : the_post(); ?>

            < ?php get_attachment_icons() ?>

            < ?php endwhile; else: ?>

            < ?php endif; ?>

          • Tony says:

            I discovered that the shortcode works correctly if you “return” the string but the calling the function from the php does not work with “return” only if you “echo” the string. So note the new code above and call the function with < ?php get_attachment_icons($echo=true); ?> and the shortcode will use “return” by default.

    4. Veets says:

      This is really neat, but does not seem to work with WP 2.9.2 I can only get it working using [attachment icons] method.

    5. VAHID says:

      Tony REALLY THANKS. I need it.

    6. Nice post man. Putting this code in the functions.php file is a really good call, especially when you want to check several file types. Thanks for sharing!

    7. Max Surguy says:

      Thank you very much for making this available. It does the job fine ! Just two things I’ve noticed : if you add atachments to the post then remove the attachments from the post, they will still appear on the post after you publish it, is there a way to get rid of that ? Also for the audio files you have an extra line of code, please delete $sAttachmentString .= “”;
      for the code to work properly. Thanks

    8. Maggy says:

      Hi! Super File! But, i’ve got the attachment two times – one in the text an one at the position of . But ich only want a icon in front of the textlink to the file – does this works too?

    9. Manas says:

      We need to upload a different file format, namely .enl, is it possible to do it here on 2.9.2? Help would be appreciated greatly.

      Thanks

      • Tony says:

        You’d just need to figure out what the mime type is for .enl and you could add that to the function. Upload an .enl using the media attachment in WordPress admin and it should show you the mime type you need.

    10. I need to make an if statment just to inserv some divs within the icon show up justi like:

      what condition should i use for knowing that an icon will show up and then print other stuff?
      thank you

    Leave a Reply