Get ID of “root-page”

I have an url that looks like this
http://apploadny.appload.nu/tjanster/webbutveckling/
I want to get the ID of the page “tjanster”, how can i do that?

Related posts

Leave a Reply

2 comments

  1. I think what you need is:

    <?php 
    $post_id = $post->ID; //or somehow get the current post ID.
    $ancestors = get_post_ancestors($post_id)  
    //$ancestors is an array of post IDs starting with the current post going up the root
    //'Pop' the root ancestor out or returns the current ID if the post has no ancestors.
    $root_id = (!empty($ancestors) ? array_pop($ancestors): $post_id);
    

    For more info check: http://codex.wordpress.org/Function_Reference/get_post_ancestors

  2. I think a better solution than @alexleonard ‘s is to use the parent_id parameter of the post object.

    $parent = ( $post_obj->parent_id != 0 ) ? $post_obj->parent_id : false;
    

    Haven’t tested that, so make sure you check for spelling mistakes and such.