0

How do I get the id of the most recent wordpress audio media upload. The reason for this is that I want to use audio cover images/ featured images as a post featured image. Do I need to retrieve the ID of the thumbnail in the audio.

I tried the code below but it returned error

    $attachments = get_posts( array(
    'post_type' => 'attachment',
    'posts_per_page' => 1,
    'post_status' => null,
    'post_mime_type' => 'audio'
) );
    foreach ( $attachments as $attachment ) {
        $post_id = get_post_thumbnail_id( $attachment->ID);
    }
1
  • Edit your question and include the error.
    – shanebp
    Commented Dec 6, 2020 at 22:26

2 Answers 2

0

As you're trying to get the ID of an attachment, functions like get_post_thumbnail_id() won't work on an attachment post because itself is the attachment.

You should be able to get the ID simply with

$post_id = $attachment->ID;
2
  • Here's my my overall code. //this is called on saving page/post add_action('save_post', 'force_featured_image'); function force_featured_image( $post_id ){ $attachments = get_posts( array( 'post_type' => 'attachment', 'posts_per_page' => 1, 'post_status' => null, 'post_mime_type' => 'audio' ) ); foreach ( $attachments as $attachment ) { $postid = get_post_thumbnail_id($attachment->ID); //set the featured image set_post_thumbnail( $post_id, $postid ); } } Commented Dec 7, 2020 at 4:40
  • get_post_thumbnail_id(); also works on attachment like audio because audios has featured images Commented Dec 7, 2020 at 4:45
0

//this is called on saving page/post add_action('save_post', 'force_featured_image'); function force_featured_image( $post_id ){ $attachments = get_posts( array( 'post_type' => 'attachment', 'posts_per_page' => 1, 'post_status' => null, 'post_mime_type' => 'audio' ) ); foreach ( $attachments as $attachment ) { $postid = get_post_thumbnail_id($attachment->ID); //set the featured image set_post_thumbnail( $post_id, $postid ); } } This code fixed it. Everything is now working fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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