Save yourself a loop with get_posts
and 'fields' => 'ids'
.
// Default Query
function do_query($args = null) {
$default_args = array(
'numberposts' => -1,
'posts_per_page' => -1,
'post_status' => 'publish',
'fields' => 'ids',
);
if (null !== $args && !empty($args))
$args = array_merge($default_args, $args);
else
$args = $default_args;
return get_posts($args);
}
// Customize Query
$post_ids = do_query (
array(
'post_type' => 'products',
'meta_key' => 'price',
'orderby' => 'meta_value_num',
'order' => 'ASC',
));
// Search for the index of the ID / prev / next
$currentID = get_the_ID();
$currentINX = array_search( $currentID, $post_ids);
$count = count($post_ids);
$prevINX = $currentINX - 1;
if ( $prevINX < 0 ) $prevID = FALSE;
else $prevID = $post_ids [ $prevINX ];
$nextINX = $currentINX + 1;
if ( $nextINX >= $count ) $nextINX = FALSE;
else $nextID = $post_ids [ $nextINX ];
// Output links
if ( $prevID ) {
$link = get_permalink ( $prevID );
echo "<a href=\"${link}\">previous product</a>";
}
if ( $nextID ) {
$link = get_permalink ( $nextID );
echo "<a href=\"${link}\">next product</a>";
}