Based on the answer by @jan-becker I build this snippet. This works for me:
/*
* Get the next/prev image id inside c-tax: my_snapshot_position_ctax
*/
function my_return_relative_attachment_id( $this_post_ID, $prev = true ) {
global $post;
// overwrite global $post variable
$post = get_post( $this_post_ID );
// filter sql query to work with attachment
add_filter( 'get_next_post_where', 'my_filter_next_prev_post_where_query', 10, 3 );
add_filter( 'get_previous_post_where', 'my_filter_next_prev_post_where_query', 10, 3 );
// Get the new post object
$adjacent_post = get_adjacent_post( true, array(), $prev, 'my_snapshot_position_ctax' );
// reset global $post variable
wp_reset_postdata();
// remove sql query filter
remove_filter( 'get_next_post_where', 'my_filter_next_prev_post_where_query', 10 );
remove_filter( 'get_previous_post_where', 'my_filter_next_prev_post_where_query', 10 );
// check if returned value is a post
if ( ! is_object( $adjacent_post ) ) {
// not a post, return an empty string
return '';
}
// return the post id
return $adjacent_post->ID;
}
/*
* Filter to modify sql query because attachments have different post status value
*/
function my_filter_next_prev_post_where_query( $sql_query, $in_same_term, $excluded_terms ) {
// replace 'publish' with 'inherit' because we work with attachments
$sql_query = str_replace( 'publish', 'inherit', $sql_query );
// return the modified query string
return $sql_query;
}
Maybe moving the filter into the function above makes less code. But this is more readable to me.