1

I'm trying to include a "Next Service" button on a website that hopefully take you to the next page under the Services page (Parent) so no matter which service you are on, it can loop through to the next (regardless if it's the first or last page).

However the code I have does that but when it gets to the last one, it carries on to the next page - regardless of the fact it's not under 'Services'.

<?php 
    $nextPost = get_next_post();
    if($nextPost) {
        $nextPostID = $nextPost->ID;
?>
    <a href="<?php echo get_permalink( $nextPostID ); ?>" >
        ID <?php echo get_the_id( $nextPostID ); ?> - <?php echo get_the_title( $nextPostID ); ?>
    </a>
<?php } else {
        $first_post = get_posts( array(
            'post_type' => 'page',
            'posts_per_page'   => 1,
            'order' => 'ASC'
        ) );
        ?>
        <a href="<?php echo get_permalink( $first_post[0]->ID ); ?>" >
            First: <?php echo get_the_title( $nextPostID ); ?>
        </a>
<?php } ?>
<?php wp_reset_postdata(); ?>
  • In your else case you try to fetch the next page when there is no next page, what are you expecting it to link to? And if it's the first page that's a child of the parent, you never mention the parent, why would it know what you meant if you don't explicitly say so? – Tom J Nowell Dec 4 '19 at 16:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.