How to retrieve images attached to post through media library?

I have been struggling to retrieve image attachments to specific post without success until I found that images inserted into the post via media library are not treated as attachments. That is, you should first upload images to the media library (even if they exists there already) and then insert into the post. Then they are treated as attachments and may be retrieved with this code:

    ?php
$args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' =>'any', 'post_parent' => $post->ID ); 
$attachments = get_posts( $args );
if ( $attachments ) {
    foreach ( $attachments as $attachment ) {
        echo apply_filters( 'the_title' , $attachment->post_title );
        the_attachment_link( $attachment->ID , false );
    }
}
?>

I believe that this is the problem with attachments.
However, my question is how can I retrieve images inserted into the post via the media library not uploading images each time?

Thanks

Read more here: How to retrieve images attached to post through media library?

Leave a Reply

Your email address will not be published. Required fields are marked *