Skip to content

Instantly share code, notes, and snippets.

@mostafasoufi
Last active September 6, 2017 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mostafasoufi/b4f52138da72b6718df1510b3e2bd581 to your computer and use it in GitHub Desktop.
Save mostafasoufi/b4f52138da72b6718df1510b3e2bd581 to your computer and use it in GitHub Desktop.
Get next & previous post in WordPress
<?php
/**
* Get Next & Previous post
*
* @param $post_id
* @param $category_id
* @param string $taxonomy
*
* @return array
*/
function get_nextprev_post( $post_id, $category_id, $taxonomy = 'category' ) {
// Get posts order by post date
$args = array(
'post_type' => 'maddahi',
'order' => 'DESC',
'post_status' => 'publish',
'posts_per_page' => 0,
'ignore_sticky_posts' => 1,
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'id',
'terms' => $category_id,
)
),
);
$posts = get_posts( $args );
// get IDs of posts retrieved from get_posts
$ids = array();
foreach ( $posts as $post ) {
$ids[] = $post->ID;
}
// get and echo previous and next post in the same category
$thisindex = array_search( $post_id, $ids );
$prev_id = isset( $ids[ $thisindex - 1 ] ) ? $ids[ $thisindex - 1 ] : 0;
$next_id = isset( $ids[ $thisindex + 1 ] ) ? $ids[ $thisindex + 1 ] : 0;
return array( 'next' => $next_id, 'prev' => $prev_id );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment