Last active
January 13, 2017 23:56
-
-
Save robertpassaro/b56f6d70daf3762b6d4c8b33c34257d6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Handy function to get next/prev post of any post type, based on any ordering criteria | |
function fq_get_nearest_posts( $post_type=null, $orderby='menu_order', $order='ASC' ) { | |
$args = array( | |
'post_type' => $post_type ? $post_type : get_post_type(), | |
'orderby' => $orderby, | |
'order' => $order, | |
'posts_per_page' => -1, | |
); | |
$q = new WP_Query( $args ); | |
$keys = array(); | |
$posts = array(); | |
while ( $q->have_posts() ) : $q->the_post(); | |
$keys[] = $q->post->ID; | |
$posts[] = $q->post; | |
endwhile; | |
wp_reset_postdata(); | |
// Identify the position of the current product within the $posts-array | |
$current = array_search( get_the_ID(), $keys ); | |
// Identify ID of previous product | |
$prev = $posts[$current-1]; | |
if( !$prev ) { | |
$p = $posts; | |
$prev = array_pop( $p ); | |
} | |
// Identify ID of next product | |
$next = $posts[$current+1]; | |
if( !$next ) { | |
$n = $posts; | |
$next = array_shift( $n ); | |
} | |
return array($prev,$next); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment