Get attachment thumbnail from get_posts function

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);
    }

Topic featured-post Wordpress

Category Web


//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.


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;

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.