Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

2 Answers 2

up vote 4 down vote accepted

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

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) –  m0r7if3r Feb 24 '12 at 13:19

Your Answer

 
discard

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.