Last active
September 25, 2024 13:47
-
-
Save kartick14/661805b1f0fd4c6eca21243c5a353332 to your computer and use it in GitHub Desktop.
create next previous post for custom post type
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
// create next previous page for custom post type | |
function get_prevnext_custompost($post_ID, $postType, $taxonomy, $term) { | |
if($taxonomy){ | |
$args = array( | |
'post_type' => $postType, | |
'posts_per_page' => -1, | |
'post_status' => 'publish', | |
'tax_query' => array( | |
array( | |
'taxonomy' => $taxonomy, | |
'field' => 'term_id', | |
'terms' => $term | |
) | |
) | |
); | |
}else{ | |
$args = array( | |
'post_type' => $postType, | |
'posts_per_page' => -1, | |
'post_status' => 'publish' | |
); | |
} | |
$all_posts = get_posts($args); | |
$next_post_id = null; | |
$prev_post_id = null; | |
if(!empty($all_posts)){ | |
//Get total post in the array | |
$post_id_array = []; | |
foreach ($all_posts as $postKey => $postValue) { | |
$post_id_array[] = $postValue->ID; | |
} | |
//echo '<pre>'; print_r($post_id_array); echo '</pre>'; | |
// check current post in the array and return its key index | |
$currentPostkey = array_search ($post_ID, $post_id_array); | |
//echo '$currentPostkey: '.$currentPostkey; | |
// Get total element in the array | |
$totalArrayElement = count($post_id_array); | |
//echo '$totalArrayElement: '.$totalArrayElement; | |
//echo '$post_ID: '.$post_ID; | |
//Calculate next and previous id | |
if($totalArrayElement > 1){ | |
if($currentPostkey && $currentPostkey == 0){ | |
$next_post_id = $post_id_array[$currentPostkey + 1]; | |
$prev_post_id = $post_id_array[$totalArrayElement - 1]; | |
}elseif($currentPostkey && $currentPostkey + 1 == $totalArrayElement){ | |
$prev_post_id = $post_id_array[$currentPostkey - 1]; | |
$next_post_id = $post_id_array[0]; | |
}else{ | |
$next_post_id = $post_id_array[$currentPostkey + 1]; | |
$prev_post_id = $post_id_array[$currentPostkey - 1]; | |
} | |
} | |
} | |
return array($prev_post_id, $next_post_id); | |
} | |
//========================================================================================= | |
// Apply on template | |
list($previousPostId, $nextpostId) = get_prevnext_custompost($pdIds, 'ebook', '', null); | |
$next_post = get_post($nextpostId); | |
if ( !empty( $next_post ) ) { | |
$next_post_url = get_permalink( $next_post->ID ); | |
} | |
$prev_post = get_post($previousPostId); | |
if ( !empty( $prev_post ) ) { | |
$prev_post_url = get_permalink( $prev_post->ID ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment