0

To get the image url from a Post Thumbnail in WordPress to display it in a template, I would use:

<?php $image_id = get_post_thumbnail_id(); $image_url = wp_get_attachment_image_src($image_id,'large'); $image_url = $image_url[0]; ?><?php echo $image_url;?>

I'm trying to do the same for a MP3 uploaded to a post.

I had a snippet a while back to get it done, but I don't know what happened to it.

How can I do the same for a MP3 uploaded to a post?

1

Assuming you do know the attachment $id, you can use wp_get_attachment_url():

  • <?php wp_get_attachment_url( $id ); ?>

If you need to determine the attachment $id, you can use get_posts():

global $post;
$audio_attachments = get_posts( array(
    'post_parent' => $post->ID,
    'post_type' => 'attachment',
    'post_mime_type' => 'audio'
) );

If you have multiple (or unknown number of) audio attachments, you can loop through to get the URLs:

$audio_attachment_urls = array();

foreach ( $audio_attachments as $audio_attachment ) {
    $audio_attachment_urls[] = wp_get_attachment_url( $audio_attachment->ID );
}

Or, if you know there is only one audio attachment:

$audio_attachment_url = wp_get_attachment_url( $audio_attachments[0]->ID );
  • Doesn't work, it's not displaying the MP3 URL. – Chozen Nov 14 '12 at 5:58
  • What did you try? Where did you try it? What data did you get returned at each point? e.g. what did you get returned for $audio_attachments? – Chip Bennett Nov 14 '12 at 12:50
  • What did you figure out? Please post your solution as an answer. – Chip Bennett Jan 10 '13 at 0:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.