Last active
September 6, 2017 10:25
-
-
Save mostafasoufi/b4f52138da72b6718df1510b3e2bd581 to your computer and use it in GitHub Desktop.
Get next & previous post in WordPress
This file contains hidden or 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
<?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