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?

2 Answers 2


I think what you need is:

$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

  • Hope you don't mind the edits :D Commented Feb 24, 2012 at 10:45
  • Thank you very much! I tried alexleonard's solution first, and it worked, but then i ran into the issue when im at "subpages" i still want to display the "grandparents" menu. It works great now with the edit :) Thank You! Commented Feb 25, 2012 at 9:46
  • Please accept this answer (using the checkmark beneath the question up/down voting buttons), if it resolves your problem. Commented May 22, 2012 at 15:45

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.

  • alexleonard's method will get the top-level parent (parent of parent of parent, etc.), which seems to be what Anton wants.
    – user66
    Commented Feb 24, 2012 at 12:35
  • @AdamBackstrom I'm not sure that that's the case...I think the question could be read either way (having reread it, I can see your point though)
    – mor7ifer
    Commented Feb 24, 2012 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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