Modify Wordpress search results to display image based on ID

I'm trying to modify the search results to enable it to display the image ID I've searched for i.e. '07547' and also the post the page is on. I've got it working to an extent - it displays the page in the results and an image but the only problem its the first image in the gallery and never the exact image I want. This is what I'm currently using:


if (
    $attachments = get_posts([
        "post_type" => "attachment",
        "post_mime_type" => "image",
        "numberposts" => 1,
        "post_status" => null,
        "post_parent" => $post->ID,
foreach ($attachments as $attachment) {
    echo wp_get_attachment_image(
        "Link to image attachment"


Any help would be greatly appreciated!