Get Adjacent Images – More WordPress Functions

Get the adjacent photo, man.

WordPress, just get the adjacent image links. I’ll tell you what to do with them!

WordPress is normally great about providing functions that have a return and an echo version.  In WordPress, if a function has the prefix get_, then it does not echo (print it into the content), but rather returns the result so that it can be saved as a variable, like so:  $example = get_example();

There are some functions that only have echo capability, so I wanted to share my work-around with you all.

Updated image_link functions

  • adjacent_image_link() » get_adjacent_image_link()
  • previous_image_link() » get_previous_image_link()
  • next_image_link() » get_next_image_link()

To add the functions, paste the following code in your theme’s functions.php file:

// These functions are copied directly from wp-includes/media.php
// and modified to return the result instead of echo it.
function get_adjacent_image_link($prev = true) {
	global $post;
	$post = get_post($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;
	$k = $prev ? $k - 1 : $k + 1;
	if ( isset($attachments[$k]) )
		return wp_get_attachment_link($attachments[$k]->ID, 'thumbnail', true);
}
function get_previous_image_link() {
	return get_adjacent_image_link(true);
}
function get_next_image_link() {
	return get_adjacent_image_link(false);
}

Now you can use these functions on your website.  Any questions? 🙂

Author: Zack Katz

Zack Katz is the President of Katz Web Services and the developer of WordPress plugins with over 700,000 downloads. He lives in Southwest Colorado with his wife and two cats.

4 thoughts on “Get Adjacent Images – More WordPress Functions”

  1. I’d do something like this instead:
    function get_previous_image_link()
    {
    $args = func_get_args();
    ob_start();
    call_user_func_array(‘previous_image_link’,$args);
    return ob_get_clean();
    }
    Let me know what you think.
    Francesco.

Leave a Reply

Your email address will not be published. Required fields are marked *