How to get $attachment->ID in custom functions

To get the attachment ID, you need to get the post attachments using get_posts() with the post_type being ‘attachment’ and the post_parent being the ID of the post you’re interested in getting the attachments from.

namespace StackExchange\WordPress;
function the_post( \WP_Post $post, \WP_Query $query ) {
  //* Get post attachments
  $attachments = \get_posts( [
    'post_type'      => 'attachment',
    'posts_per_page' => -1,
    'post_parent'    => $post->ID,
    'exclude'        => get_post_thumbnail_id()
  ] );
  //* There can be more than one attachment per post, so loop through them
  foreach( $attachments as $attachment ) {
    //* Maybe do some sanity checks here
    $parsed = parse_url( \wp_get_attachment_url( $attachment->ID ) );
    //* Do something useful with the parsed URL
  }
}
\add_action( 'the_post', __NAMESPACE__ . '\the_post', 10, 2 );

Above, I’m using the the_post action to get the post ID of the post parent. Depending on your use case, you could use another hook and get_the_ID() to get the ID of the post parent.