Adjacent images (wordpress)

Retrieve the adjacent image links.

<?php
/**
 * Retrieve the adjacent image links.
 */
function __adjacent_image($prev = true, $text = '') {
  global $post;
  $original_post = $post;
  $post = get_post();
  $attachments = array_values(get_children([
    'post_parent' => $post->post_parent,
    'post_status' => 'inherit',
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'order' => 'ASC',
    'orderby' => 'menu_order ID',
  ]));
  $k = -1;
  foreach ($attachments as $i => $attachment) {
    if ($attachment->ID == $post->ID) {
      $k = $i;
      break;
    }
  }
  $link = '';
  if ($k >= 0) {
    $adjacent = $prev ? $k - 1 : $k + 1;
    if (isset($attachments[$adjacent])) {
      $link = wp_get_attachment_link($attachments[$adjacent]->ID, '', true, false, $text);
    }
  }
  $post = $original_post;
  return $link;
}
function __previous_image_link() {
  return __adjacent_image(true, '&larr; Previous image');
}
function __next_image_link() {
  return __adjacent_image(false, 'Next image &rarr;');
}
?>

functions.php

Output previous and next image links.

<?php
  echo __previous_image_link();
  echo __next_image_link();
?>

template.php

< toolbox