Get Adjacent Images – More WordPress Functions

August 4, 2009

in Code,WordPress

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? :-) 

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • Twitter

Related posts:

  1. Nofollow SEO for your WordPress Functions
  2. Auto-Optimize WordPress Database without a Plugin
  3. Save Coding Time by Creating Special-Case Categories in WordPress
  4. WordPress Digg Shortcode Function – As Seen on WordPress.com
  5. How to tell if your WordPress Plugin or Widget is Activated in WordPress

3 comments… read them below or add one

Bjørn Endre September 7, 2009 at 8:50 am

Thanks, mate! Exactly what I needed :D

Reply

Francesco April 26, 2010 at 10:56 am

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.

Reply

Zack Katz April 26, 2010 at 3:07 pm

@Francesco: That sounds like a good solution as well. Preferably, the function would simply be added to the WordPress core.

Reply

Leave a Comment

Previous post:

Next post: