How to get next post link of child custom post type from parent post and get next post link of parent post from the last child post?

I have a custom post type with this structure:

First Parent

  • 1st child of First Parent
  • 2ndchild of First Parent
  • 3rd child of First Parent

Second Parent

  • 1st child of Second Parent
  • 2nd child of Second Parent
  • 3rd child of Second Parent

I'm trying to make previous_post_link() and next_post_link() to work that when you are in the First Parent, the next_post_link() will go to the 1st child of First Parent and then when you are in the 1st child of First Parent, you go to the 2nd child of First Parent. When you are in the 3rd child of First Parent, you go to Second Parent when you click next and go to 2nd child of First Parent when you click back.

Basically, by clicking next and prev link, you go to every page in that sequence regardless of child or parent posts.

Right now, what happens is that when you are in the parent posts, the next_post_link() will link you to the next parent post.

Currently when you click on next:

First Parent - Second Parent.

I want it to be like this:

First Parent - first child of First Parent - second child of First Parent - third child of First Parent - Second Parent - first child of Second Parent .. and so on.

Here's what I have on my single-post-type.php

li class=nav-item
        ?php if (get_previous_post_link()) : ?
        ?php previous_post_link( '%link', 'i class=bi bi-arrow-left-square/i' ); ?
        ?php else : ?
        a class=nav-link disabled href=# tabindex=-1 aria-disabled=true i class=bi bi-arrow-left-square/i/a
        ?php endif; ?
/li
li class=nav-item
        ?php if (get_next_post_link()) : ?
        ?php next_post_link( '%link', 'i class=bi bi-arrow-right-square/i' ); ?
        ?php else : ?
        a class=nav-link disabled href=# tabindex=-1 aria-disabled=true i class=bi bi-arrow-right-square/i/a
        ?php endif; ?
/li

Topic next-post-link previous-post-link navigation custom-post-types Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.