Adjacent images (wordpress)

Retrieve the adjacent image links.

function __adjacent_image($prev = true, $text = '') {
    global $post;
    $post = get_post();
    $attachments = array_values(get_children(array(
        'post_parent' => $post->post_parent,
        'post_status' => 'inherit',
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'order' => 'ASC',
        'orderby' => 'menu_order ID'
    )));
    foreach ($attachments as $k => $attachment) {
        if ($attachment->ID == $post->ID) {
            break;
        }
    }
    $attachment_id = 0;
    if ($attachments) {
        $k = $prev ? $k - 1 : $k + 1;
        if (isset($attachments[$k])) {
            $attachment_id = $attachments[$k]->ID;
            if ($attachment_id != 0) {
                return wp_get_attachment_link($attachment_id, '', true, false, $text);
            }
        }
    }
}
function __previous_image_link() {
    return __adjacent_image(true, '← Previous image');
}
function __next_image_link() {
    return __adjacent_image(false, 'Next image →');
}

functions.php

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

template.php

< toolbox