0

I have the following structure:

  • TOP PAGE

    • SUB PAGE 1

    • --- SUB SUB PAGE 1

    • --- SUB SUB SUB PAGE 1

    • ---- SUB SUB SUB SUB PAGE 1

    • --- SUB SUB SUB PAGE 1

    • --- SUB SUB SUB PAGE 1

    • ---- SUB SUB SUB SUB PAGE 1

How can I get the TOP PAGE url from any of the SUB PAGES?

For example: Get TOP PAGE url from ---- SUB SUB SUB SUB PAGE 1

With this I can only get the previous page url and not the Top parent ulr

        if ( $post->post_parent ) {
            $parent_page_link = get_permalink( $post->post_parent ); // getting parent URL
        } 

There are many topics with related question but I can not solve my problem.

Thanks,

3

You have to do it in a loop:

$p = $post;
while ( $p->post_parent ) {
    $p = get_post( $p->post_parent );
}
$parent_page_link = get_permalink( $p->ID );

Another way is to use get_ancestors function:

$ancestors = get_ancestors( $post->ID, 'page', 'post_type' );
$root = ( ! empty( $ancestors ) ) ? end($ancestors) : $post->ID;
$parent_page_link = get_permalink( $root );    

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.