Retrieving the Next and Previous Attached Images of a WordPress Post
Below you'll find a pair of helper functions that let you fetch the next and previous images attached to a given post. Each function looks up the attachment's parent post and then queries the database for the closest image attachment by ID.
<?php
function get_post_next_attached_image( $attachment_id ) {
global $wpdb;
$attachment = get_post( $attachment_id );
$next_attached_image = $wpdb->get_row("SELECT * FROM " . $wpdb->posts . " WHERE ID = (SELECT MIN(ID) FROM " . $wpdb->posts . " WHERE post_parent = '" . $attachment->post_parent . "' AND post_mime_type LIKE 'image%' AND ID > '" .$attachment_id . "' ORDER BY menu_order, ID);");
return $next_attached_image;
}
function get_post_previous_attached_image( $attachment_id ) {
global $wpdb;
$attachment = get_post( $attachment_id );
$previous_attached_image = $wpdb->get_row("SELECT * FROM " . $wpdb->posts . " WHERE ID = (SELECT MAX(ID) FROM " . $wpdb->posts . " WHERE post_parent = '" . $attachment->post_parent . "' AND post_mime_type LIKE 'image%' AND ID < '" .$attachment_id . "' ORDER BY menu_order, ID);");
return $previous_attached_image;
}
?>Filed under post attachments and Wordpress.
Tweet ShareReader Discussion
View this comment · View reply
Leave a Reply
Required fields are marked *. Your email address will never be published or shared.
Comment, Name*, Email*, Website
Leave a ReplyRecent Posts
Recent Comments
- María José on WordPress plugin “UBM Premium”
- Nicolas on WordPress plugin “UBM Premium”
- Tobias on WordPress plugin “UBM Premium”
- antaly on WordPress plugin “Useful Banner Manager” new 1.5 version
- Steve on WordPress plugin “Useful Banner Manager”
Most Commenting Visitors
- JDB (13 comments)
- Laurens V. (10 comments)
- wifi (9 comments)
- Droid (9 comments)
- Marcelo (8 comments)
Helpful Resources
If you need some help with envision webhosting and actualtests - toefl - certification, then get the latest act prep pass4sure compiled by our certified experts to help you pass selftestengine mcat practice test in first attempt. You can also download passguide - gre - certification.
My Plugins
My Pages







Tags
automatically comments widget Google plus file ie6 sort categories passing time text highlight Domtooltips custom fields new version quick navigation plugin bugfix lightbox 2 counter installation email checkboxes explanatory dictionary Wordpress tooltips outbound link manager greetings seo share buttons texts check/uncheck Twitter JavaScript banner manager RSS PHP outbound links Blorner quick navigation panel links matching Facebook running line NextGEN visitors
Partners




Commenter Avatars






