I'm trying to list all of my posts in a page(with post's content). Everything is showing correctly but the audio player which uses post id to get the URL of an attachment in the post is not showing. I'm using the following code to get the post ID:-

global $wp_query;
$postID = $wp_query->$post->ID;
$file_id = get_post_meta( $post->ID, sound_s, true );
$fileUrl = wp_get_attachment_url($file_id);
$attr = array(
'src'      => $fileUrl,
'loop'     => '',
'autoplay' => '',
'preload'  => 'none'
echo wp_audio_shortcode( $attr );

It works in the post itself but when I try to list it in the page the post ID shows page Id instead. Please help me with this.

  • How do you query and output the posts? – Milo Sep 12 '18 at 5:00
  • 1
    $postID = wp_quey->post->ID; - that's not valid PHP. Please post the code you're actually using. – Gray Sep 12 '18 at 5:26
  • @Gray sorry for the spelling mistake. But the question is still same. – Shikhar Mishra Sep 12 '18 at 6:20
  • $postID = wp_query->post->ID; is still invalid PHP and will throw a fatal error. Why don't you just post exactly what you have? – Gray Sep 12 '18 at 6:37
  • @Gray I think it's right now. – Shikhar Mishra Sep 12 '18 at 7:11

You should not use globals directly. There are some nice wrapper functions in the WordPress API. If you want to retrieve the ID of the current post or page just use get_the_ID().

Without any test ... you could write the functionality in this way:

$file_id  = get_post_meta( get_the_ID(), 'sound_s', true );
$file_url = wp_get_attachment_url( $file_id );

echo wp_audio_shortcode( [ 'src' => $file_url ] );

I don't know much about the plugin that you use but why don't you loop just over the list of posts:

$posts = get_posts();
foreach ( $posts as $item ) {
    $file_id  = get_post_meta( $item->ID, 'sound_s', true );
    $file_url = wp_get_attachment_url( $file_id );

    echo wp_audio_shortcode( [ 'src' => $file_url ] );
  • Thanks for your solution but when I'm trying to loop through posts, It gives me the correct post ID however when trying to echo $file_url. It is showing nothing. Do anyone know why It's happening – Shikhar Mishra Sep 13 '18 at 5:20
  • Is there a value in $file_id? – realloc Sep 13 '18 at 15:43
  • No It's returning 0 when I'm trying to var_dump($file_id) – Shikhar Mishra Sep 14 '18 at 3:27

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.