Display Audio Attachment URL in WordPress Template

When designing the music page for my site iHipHopMusic.com, I had hit a road block. When users uploaded music to the site, I was using the update_post_meta function to pass the audio to a custom field so I could call the URL directly.

But for some reason I didn't want to stream my files from a custom field anymore, instead I wanted to call the the audio URL directly as an attachment the way you would with images attached to a pot.

I took to Google and I was surprised to find that it wasn't as easy to find as I thought it would be, after trolling for a few hours and asking some questions on a few boards I was able to peace together a working way of getting it done. It's works similar to calling image src of a featured image for a post.

Check out the code below.

It's quite a bit of code, more than I thought I would need for such a simple task, if you guys have a better method please suggest it below.

I'm still very much a noob when it comes to PHP, Web Designer by trade not a Programmer.

Thanks, hope this was helpful.

With condition
        
<?php $audio = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'audio' ) ); ?>
<?php if ( empty( $audio ) ) : ?>
<?php else : ?>
        <?php foreach ( $audio as $attachment_id => $attachment ) : ?>
        <?php echo wp_get_attachment_url( $attachment_id, 'full' ); ?>
        <?php endforeach; ?>
<?php endif; ?>        
    
Without condition
        
<?php $audio = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'audio' ) ); ?>
<?php foreach ( $audio as $attachment_id => $attachment ) : ?>
<?php echo wp_get_attachment_url( $attachment_id, 'full' ); ?>
<?php endforeach; ?>        
    

2 comments