Unable to get all the Posts Attachments

I think you’d have an easier time if you used: $wpdb

global $wpdb;
$table_name="posts"; // change this to your post-table name, it may be something different.
$values = $wpdb->get_results( "SELECT * FROM $table_name where post_type = attachment");
foreach ($values as $value){
  print_r($value);
}

If you’re seeing unexpected values, then you’ll need to figure out if there’s anything different about the unexpected values.

By that I mean, are the unexpected values coming from posts which have been deleted? Or attachments that have been moved to the trash but not completely removed? Maybe have a poke around and see if you can find the unexpected attachments and see if you can delete them.

To troubleshoot this further, it would be good to know what’s happening in the $wp_query outside of where you’re calling this function. using global $wp_query; var_dump($wp_query); exit; can tell you more.