How to use previous/next image link, ignoring parent posts/attachments?

There may be a better way to do this, but this is where I’ve got to so far. I’m very happy for anyone who knows WP better to tell me how it could be better!

My gallery page contains this shortcode:


I’ve restricted it to term 943 in a custom taxonomy called media_category. If using something like this it also needs to be in the $args below.

Note that the orderby and order affect how we fetch the next/previous image in the code below.

In my image.php template I have this near the start:

// Initial query args used for both next and previous:
$args = array(
    'post_type' => 'attachment',
    'post_mime_type' => 'image/jpeg,image/gif,image/jpg,image/png',  
    'posts_per_page' => 1, 
    'post_status' => 'inherit',
    // The same orderby as in our gallery shortcode:
    'orderby' => 'post_date',
    // The same taxonomy as in our gallery shortcode:
    'tax_query' => array(
        'taxonomy' => 'media_category',
        'field' => 'term_id',
        'terms' => 943,
    ),
    'date_query' => array()
);

// Add query args for finding previous image:
$args['order'] = 'DESC';
$args['date_query'] = array('before' => $post->post_date);

// Get previous image:
$prev_query = new WP_Query( $args );

while ($prev_query->have_posts()) {
    $prev_query->the_post();
    // Set previous image:
    $prev_image = get_post();
}
wp_reset_postdata();

// Add query args for finding next image:
$args['order'] = 'ASC';
$args['date_query'] = array('after' => $post->post_date);

// Get next image:
$next_query = new WP_Query( $args );

while ($next_query->have_posts()) {
    $next_query->the_post();
    // Set next image:
    $next_image = get_post();
}
wp_reset_postdata();

And then in the location in the template where I want the links:

<?php
if ($prev_image) {
    ?>
    <a href="https://wordpress.stackexchange.com/questions/282575/<?php the_permalink($prev_image); ?>" title="<?php echo get_the_title($prev_image); ?>">Previous image</a>
<?php
}
if ($next_image) {
    ?>
    <a href="<?php the_permalink($next_image); ?>" title="<?php echo get_the_title($next_image); ?>">Next image</a>
<?php
}
?>

I’ve hacked this together from various examples and it seems to work… if you know of improvements, do let me know!