Skip to content

Instantly share code, notes, and snippets.

@LL782
Last active April 8, 2022 23:07
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save LL782/3551634 to your computer and use it in GitHub Desktop.
Save LL782/3551634 to your computer and use it in GitHub Desktop.
Next and Prev Page Siblings - Wordpress
<?php
function getId($page) { return $page->ID; }
$ancestors = get_post_ancestors( $post->ID );
$parent = ($ancestors) ? $ancestors[0] : null;
if ($parent) :
$siblingIds = array_map( "getId", get_pages('child_of='. $parent .'&sort_column=menu_order&sort_order=asc') );
$current = array_search( get_the_ID(), $siblingIds );
$prevId = ( isset($siblingIds[$current-1]) ) ? $siblingIds[$current-1] : '';
$nextId = ( isset($siblingIds[$current+1]) ) ? $siblingIds[$current+1] : '';
?>
<nav id="pagination">
<?php if (!empty($prevId)) : ?>
<div class="alignleft">
<a
href="<?php echo get_permalink($prevId); ?>"
title="<?php echo get_the_title($prevId); ?>"
class="previous-page"
>&lt;&nbsp;&nbsp;Previous</a>
</div>
<?php endif; ?>
<?php if (!empty($nextId)) : ?>
<div class="alignright">
<a
href="<?php echo get_permalink($nextId); ?>"
title="<?php echo get_the_title($nextId); ?>"
class="next-page"
>Next&nbsp;&nbsp;&gt;</a>
</div>
<?php endif; ?>
</nav>
<?php endif; ?>
@quasiDigi
Copy link

hi @LL782,

I think there is a small errata in the code, on lines 12 and 13:

$prevId = ( isset($pages[$current-1]) ) ? $pages[$current-1] : '';
$nextId = ( isset($pages[$current+1]) ) ? $pages[$current+1] : '';

should be:

$prevId = ( isset($siblingIds[$current-1]) ) ? $siblingIds[$current-1] : '';
$nextId = ( isset($siblingIds[$current+1]) ) ? $siblingIds[$current+1] : '';

Thank you for share 👍

@LL782
Copy link
Author

LL782 commented Sep 23, 2020 via email

@quasiDigi
Copy link

@LL782, I made a fork but can't find a way to make you a PR over here. Probably because it's a single file and not a repository. It's only two words that need to be changed. You actually forgot to change some variable names last time you adapted the code.

@LL782
Copy link
Author

LL782 commented Oct 21, 2020

@quasiDigi thanks for pointing that out! I've edited the file now. Cheers for your input 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment