Here is an example of functions to get next and previous attached images of the post:

<?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;
}
?>
Share

2 Comments on Get post next and previous attached images in WordPress

  1. Peter says:

    this solution doesn’t work for me ;/. I’ve spent almost 4 hours to try figure out how to fix this. The site is http://www.webdesignerfromchicago.com .please help me somehow.

  2. Hi Peter,

    Sorry, but I couldn’t understand what was the problem in that site. Please explain more.

    Thanks.

Leave a Reply

Info