You can try this one-liner, within the loop, instead of all your above code:
$ids = join( ',', wp_list_pluck( get_attached_media('image' ), 'ID' ) );
where we pluck out the ID’s from the get_attached_media()
output.
Another approach would be to use:
$ids = join( ',', get_attached_media( '_image_ids' ) );
where we’ve introduced a new input parameter _image_ids
, supported by the use of the following plugin:
/**
* Plugin Name: Enhance the get_attached_media() function.
* Description: Support for the custom '_image_ids' parameter.
* Plugin URI: http://wordpress.stackexchange.com/a/169152/26350
* Author: birgire
* Version: 0.0.1
*/
add_filter( 'get_attached_media_args', function( $args, $type, $post ) {
if( '_image_ids' === $type )
{
$args['post_mime_type'] = 'image';
$args['fields'] = 'ids';
}
return $args;
}, 10, 3 );