pagination – How to paginate through child and grandchild pages (current code only works with child)

Question

I want to paginate child and grandchild pages of a parent page. My code works, but it skips granchild pages and goes to the next child page. How can I change this code to also include grandchildren?

  1. Parent page
  2. Child 1
  3. Child 2
  4. Grandchild (child of 2)
  5. Child 3

On Child 1, I want “next” to go to Child 2, and nothing as “previous. On Child 2 I want Grandchild to be the “next.” On Grandchild, I want “next” to be Child 3 and “previous” to be Child 2.

<?php
$args = array(
    'child_of' => $post->post_parent,
    'parent' => $post->post_parent,
    'sort_column' => 'menu_order',
);

$pagelist = get_pages($args);
$pages = array();
foreach ($pagelist as $page) {
  $pages[] += $page->ID;
}

$current = array_search($post->ID, $pages);
?>

<?php if (isset($pages[$current-1])) { ?>
  <?php $prevID = $pages[$current-1]; ?>

  <a href="<?php echo get_permalink($prevID); ?>">Previous</a>

<?php }

if (isset($pages[$current+1])) { ?>
<?php $nextID = $pages[$current+1]; ?>

  <a href="<?php echo get_permalink($nextID); ?>">Next</a>

<?php } ?>

0
Elizabeth 4 weeks 2022-12-30T16:26:56-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse