Skip to content

Instantly share code, notes, and snippets.

@stephenh1988
Created June 7, 2012 10:19
Show Gist options
  • Save stephenh1988/2888049 to your computer and use it in GitHub Desktop.
Save stephenh1988/2888049 to your computer and use it in GitHub Desktop.
Get's the next/previous page (or hierarchical cpt) with the same parent as the current post.
<?php
/*
* Gets IDs of the previous and next siblings (pages with the same parent as current post).
* Then uses wpse5422_display_prev_next to display links to them
* Must be used inside the loop.
*
* This is my solution to: http://wordpress.stackexchange.com/a/54463/9364
*/
function wpse5422_the_page_siblings(){
$post_id = get_the_ID();
$parent_id = wp_get_post_parent_id( $post_ID );
$post_type = get_post_type($post_id);
$sibling_list = get_pages(array(
'sort_column'=>'menu_order',
'sort_order' =>'asc',
'child_of' =>$parent_id,
'post_type'=> $post_type
));
if( !$sibling_list || is_wp_error($sibling_list) )
return false;
$pages = array();
foreach ($sibling_list as $sibling ) {
$pages[] = $sibling->ID;
}
$current = array_search($post_id, $pages);
$prevID = isset($pages[$current-1]) ? $pages[$current-1] : false;
$nextID = isset($pages[$current+1]) ? $pages[$current+1] : false;
echo wpse5422_display_prev_next($prevID, $nextID);
}
/*
* Generates and returns html for displaying 'previous' and 'next' links given the post IDs.
*
* @param (int) $prevID - ID of the post that is 'previous'
* @param (int) $nextID- ID of the post that is 'next'
*/
function wpse5422_display_prev_next($prevID=false, $nextID=false){
if( empty($prevID) && empty($nextID) )
return false;
$html = '<div class="navigation">';
if( !empty($prevID) ){
$html .= '<div class="alignleft">';
$html .= '<a href="'.get_permalink($prevID).'">Previous</a>';
$html .= '</div>';
}
if( !empty($nextID) ){
$html .= '<div class="alignright">';
$html .= '<a href="'.get_permalink($nextID).'">Next</a>';
$html .= '</div>';
}
$html .= '</div><!-- .navigation -->';
return $html;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment