Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.