Adding MP3 Files to WordPress Themes

This is a guest post from the talented Joseph Hinson. Interested in seeing your name up here too? Get in touch!

In this post I’m going to talk about how to use WordPress’ attachment functionality to automatically detect and wrap mp3s in a player.

If you want to your mp3s to automatically be wrapped in a player, you can incorporate that functionality into your theme by using the JW Player (or any other embeddable player) and WordPress’ get_children() function.

Before we get started, let me explain why this might be a better option than using a plugin:

  1. All you have to do is upload the mp3(s) and the theme takes care of the rest.
  2. You get to learn more about get_children(), which you can do a lot with.
  3. The JW Player can handle video and audio, so with a slight code modification, you’re in business for playing movies as well as music.
  4. You don’t have to install a plugin that might break in a future version of WordPress.

The Player

MP3 Players in Action

There are several embeddable mp3 players that you can use. I was using google reader’s player for awhile until I realized it doesn’t work well in IE, so I decided to go a different route here and use the jw-player. Longtail Video’s JW Player is free for non-commercial use and works in seemingly every browser. It’s even got an easy setup wizard if you need help getting your embed code worked out. And though I use the term mp3 throughout this tutorial, the JW Player supports m4a as well.

The embed code for a single song looks like this:

<object width='470' height='24' id='single2' name='single1'>
	<param name='movie' value='player.swf'>
	<param name='allowfullscreen' value='true'>
	<param name='allowscriptaccess' value='always'>
	<param name='wmode' value='transparent'>
	<param name='flashvars' value='file=PATH-TO-YOUR-MP3'>
		<embed
		  id='single2'
		  name='single2'
		  src='player.swf'
		  width='470'
		  height='24'
		  bgcolor='#ffffff'
		  allowscriptaccess='always'
		  allowfullscreen='true'
		  flashvars='file=PATH-TO-YOUR-MP3'
		/>
</object>

In Action

The player looks like this:

I’m going to download the player and store all the files in a subdirectory of my theme called “jw”, so I’ll use the WordPress function template_url /jw/ to point to that directory. In reality, it’s http://my-site.com/wp-content/themes/my-theme/jw/.

The Code

In your template file (index.php or single.php), we’re gonna use the get_children() WordPress function to get the attachments that match a specific mime type (of audio – that will handle mp3s and m4as). The function returns an array that we’ll loop through using a PHP foreach. So, here’s what we’re gonna do:

  1. Store the array that’s generated from the function in a variable called $mp3s
  2. Check to make sure the variable $mp3s isn’t empty (that an mp3 is present as an attachment)
  3. Loop through the mp3s attached, showing each mp3 in the embedded player.

The following code should take place inside the loop:

<?php $mp3s = get_children( 'numberposts=-1&post_type=attachment&post_mime_type=audio&post_parent='.$post->ID );

	if (!empty($mp3s)) : ?>

		<?php foreach($mp3s as $mp3) : ?>
			<object width='470' height='24' id='single<?php echo $mp3->ID; ?>' name='single<?php echo $mp3->ID; ?>'>
				<param name='movie' value='player.swf'>
				<param name='allowfullscreen' value='true'>
				<param name='allowscriptaccess' value='always'>
				<param name='wmode' value='transparent'>
				<param name='flashvars' value='file=<?php echo $mp3->guid;?>'>
					<embed
					  id='single<?php echo $mp3->ID;?>'
					  name='single<?php echo $mp3->ID;?>'
					  src='<?php bloginfo('template_url'); ?>/jw/player.swf'
					  width='470'
					  height='24'
					  bgcolor='#ffffff'
					  allowscriptaccess='always'
					  allowfullscreen='true'
					  flashvars='file=<?php echo $mp3->guid; ?>'
					/>
			</object>
		<?php endforeach; ?>

	<?php endif; ?>

A few things to notice here:

  1. I’m passing a parameter to get_children of post_parent = $post->ID. This passes the ID of the page/post you’re on to the function. As long as you’re inside the loop, this will work, otherwise, you have to somehow get the ID then pass it in a different way.
  2. The parameter numberposts is set to -1, which means it will show every uploaded attachment that matches the mime type of audio. You can change this to a number if you would like to limit the amount of songs that show.
  3. I’m using $mp3->ID (the ID of the mp3 attachment itself) to make sure that each instance of the player has a unique ID, otherwise the players will break each other.

Once more, this time with Gusto!

This works well for showing the players, but what about the title and description? You can also pull that info from the attachment. In the next example we’re going to wrap each mp3 that’s attached in an li with the attachment title and description also being shown.

<?php $mp3s = get_children( 'numberposts=-1&post_type=attachment&post_mime_type=audio&post_parent='.$post->ID );

	if (!empty($mp3s)) : ?>

	<ul>

	<?php foreach($mp3s as $mp3) : ?>
		<li>
			<?php if(!empty($mp3->post_title)) : //checking to make sure the post title isn't empty ?>
				<h4 class="title"><?php echo $mp3->post_title; ?></h4>
			<?php endif; ?>

			<?php if(!empty($mp3->post_content)) : //checking to make sure something exists in post_content (description) ?>
				<p class="description"><?php echo $mp3->post_content; ?></p>
			<?php endif; ?>

			<object width='470' height='24' id='single<?php echo $mp3->ID; ?>' name='single<?php echo $mp3->ID; ?>'>
				<param name='movie' value='player.swf'>
				<param name='allowfullscreen' value='true'>
				<param name='allowscriptaccess' value='always'>
				<param name='wmode' value='transparent'>
				<param name='flashvars' value='file=<?php echo $mp3->guid;?>'>
					<embed
					  id='single<?php echo $mp3->ID;?>'
					  name='single<?php echo $mp3->ID;?>'
					  src='<?php bloginfo('template_url'); ?>/jw/player.swf'
					  width='470'
					  height='24'
					  bgcolor='#ffffff'
					  allowscriptaccess='always'
					  allowfullscreen='true'
					  flashvars='file=<?php echo $mp3->guid; ?>'
					/>
			</object>
		</li>

	<?php endforeach; ?>

	</ul>

<?php endif; ?>

Take Note

  • I’ve wrapped the p and h4 tags in if statements that check to see if the values of the title and description actually have content before the elements are created. If nothing is filled in for a description, the paragraph tag doesn’t get created.
  • Helpful Tip: You can find out what is stored in any array by using the PHP function print_r(the_array_name). It will print out a list of values stored in the array. It gets a little jumbled in the content, so view source for best results if you use this.

Done and Done. But don’t screw up now.

Once you’ve inserted the code in your theme, all you have to do to to take advantage of your new found functionality, is upload an mp3 using the “Add Media” button through the WordPress Add Post page. Once you’ve uploaded your mp3, just click “Save All Changes” and close. Don’t click “Insert into post”. For some reason, the mp3 doesn’t get registered as an attachment if you insert it into a post.

Save All Changes

Before you guys give me crap about liking Carrie Underwood, let me just disclaim that this is for my daughter’s blog.

I’ve tested this with mp3s and m4as. For some reason, my WordPress install gave me a bit of a fit when I tried m4ps, but I’m pretty sure the JW Player supports them.

Even if this functionality isn’t something you specifically need, it is still a good exercise to try this if you’ve never learned about get_children(). You can do a lot to enhance your theme with it.

What about you? Do you currently use get_children() or something similar to beef up your theme? If so, tell me about it.

Further Reading

  1. Longtail Video – Home of the JW Player
  2. WordPress Function Reference – get_children()
  3. More About Mime Types
  • Stumble It!
  • Bookmark It!
  • Tweet it!

About Joseph Hinson

Joseph Hinson is the second man of the two man team and front-end developer for Out:think Group. He lives in Virginia with his wife and daughter. When he's not working or hanging out with his family, he geeks out at his personal blog and plays xbox.

 

Discussion

  1. Cook

    April 23rd, 2010 at 11:41 AM

    good informative post….great help

  2. Jeff Crump

    April 23rd, 2010 at 12:31 PM

    Interesting stuff. I’d like this to work on an the iPhone OS. Do you know of any solutions like this that do not use Flash as the engine?

  3. Joseph Hinson

    April 23rd, 2010 at 12:48 PM

    Jeff,

    I recently was wondering the same thing. There’s an inline javascript solution called SoundManager2. It works in an iphone, but opens exclusively like youtube videos do. Seems like the best bet for iPhone though.

  4. Jeff Crump

    April 23rd, 2010 at 1:12 PM

    Cool. Thanks for the response. Much appreciated. Your site consistently gives me great articles to read.

  5. Tony Gray

    April 24th, 2010 at 4:37 AM

    This is the perfect addition to my latest article at http://www.tgrayimages.com/automate-file-attachments-on-your-wordpress-posts. I updated my article according to your sample and linked back to the page for reference. Thanks! Great idea!

  6. Web Risorsa

    April 24th, 2010 at 6:49 AM

    Superb post with nice explanation… let me try it on my blog…

  7. free FONT

    April 25th, 2010 at 3:58 AM

    thank you for the tutorial.
    keep up the good work

  8. Thiago Cavalcanti

    April 25th, 2010 at 11:30 PM

    I’m making a electronic music blog right now and this will sure come in handy.
    Thanks!

  9. Deluxe Blog Tips

    April 26th, 2010 at 5:34 PM

    Nice post. The idea of getting all attached mp3 files via get_children is cool.

    Anyway, I think creating players for each mp3 file is not good. Instead of that, we should create a playlist.

  10. benjamin a. petersen

    April 27th, 2010 at 10:13 AM

    If you wrap your print_r function in html pre tags, it will display in a nice, neat, orderly list. This is SUPER helpful for seeing details more clearly.
    IE:
    echo “

    ";
    print_r(the_array_name);
    echo  "

    “;

  11. benjamin a. petersen

    April 27th, 2010 at 10:14 AM

    ha — after the echos it is supposed to have pre tags in that last comment — looks like they were stripped out! sorry guys.

  12. Joseph Hinson

    April 27th, 2010 at 10:16 AM

    benjamin,

    I have used that method before as well and it is very helpful. Thanks for contributing!

  13. DinoThemes

    April 28th, 2010 at 12:03 PM

    Awesome info, bookmarking for future reference!

  14. Chris Janus

    April 28th, 2010 at 8:54 PM

    ah, excellent! i’m working on a punk record label site and may very well be able to use this with it! i’ll be glad to learn a little about get_children() too and see how else that can be used in wordpress.

    thank you!

  15. Tutorial Lounge

    May 1st, 2010 at 9:11 AM

    really helping and this is an future enhancement.

  16. Abu Farhan

    May 13th, 2010 at 9:11 PM

    Thanks for this post, I like this way to put auto mp3 player to wp. Usually I used plugin but this way is better

  17. bulletin

    May 17th, 2010 at 4:38 PM

    hello. I think its just me, but i just cant get this thing to work on WP.
    Im sorry but i just dont understand where im supposed to put all (one of the three provided, right?) this code.
    I tried this on single.php (pasted the code somewhere) but im not sure..
    I made “jw” floder to my theme folder, uploaded the files (player.swf, yt.swf, swfobjects.js)
    And if i upload the *.mp3 file via “add media” and close the window. I have to use the “File URL” and add it to the code but there is where it gets kind a complicated to me..
    I think im missing something here, but i just cant figure that out. Please help me out.
    Thanks

  18. Rakesh Solanki

    July 4th, 2010 at 9:14 AM

    Quite interesting tutorial for those sites which provides some kind of online help.

  19. oliver

    July 14th, 2010 at 7:22 AM

    do i need to change anything else then the mime-type to get it work with video?

  20. Joseph

    July 16th, 2010 at 8:01 AM

    oliver,

    you should only have to specify the mime type and change the height to accommodate the video.

  21. jeza

    July 16th, 2010 at 11:58 PM

    I like the idea of putting this on my blog and adding a video on top. I will try this when my blog is good again, i was hacked :(its being fixed by the next couple days :)
    jeza

  22. nikhil

    July 21st, 2010 at 6:41 AM

    Its really helpful n nice post. yes ! now i can i add my fav MP3′s to wordpress and play it from anywhere. Thanks for such wonderful post.

  23. Seon Poppcile - London

    July 27th, 2010 at 9:20 AM

    Cool! I think I have just found my new favourite wordpress plugin.. JW player all the way – going to try it out now, thanks for sharing!

Join the Conversation!

Remember: Life's not all doom and gloom, so please keep it constructive. If we've made an error or missed something big, please let us know! Learning is revisions, after all.

CommentLuv is Enabled

 

Sponsors

Advertise on Build Internet!