WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 4 down vote accepted

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

share|improve this answer
Hope you don't mind the edits :D – Stephen Harris Feb 24 '12 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! – Anton Gildebrand Feb 25 '12 at 9:46
Please accept this answer (using the checkmark beneath the question up/down voting buttons), if it resolves your problem. – Chip Bennett May 22 '12 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.

share|improve this answer
alexleonard's method will get the top-level parent (parent of parent of parent, etc.), which seems to be what Anton wants. – Annika Backstrom Feb 24 '12 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 Feb 24 '12 at 13:19

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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