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 am trying to get current page nearest parent id not top-level. For example I have added page like this:

enter image description here

Now If I am in Junior Design Award 2013 page I want to get his parent id 765 not top-level parent id 691

I have tried bellow code but I am getting top-level id which is 691.

function.php

function get_root_parent_id( $page_id ) {
    global $wpdb;
    $parent = $wpdb->get_var( "SELECT post_parent FROM $wpdb->posts WHERE post_type='page' AND post_status='publish' AND ID = '$page_id'" );
    if( $parent == 0 ){
        return $page_id;
    }else{
        return get_root_parent_id( $parent );
    } 
}

page.php

global $post;     // if outside the loop
$page_object = get_queried_object();
$page_id  = get_queried_object_id(); // Get current page id

echo $root_parent_id = get_root_parent_id( $page_id );

Any Idea?

Thanks.

share|improve this question
    
$post->post_parent ? –  Sisir May 7 at 9:06

1 Answer 1

up vote 1 down vote accepted

try this.

global $post;     // if outside the loop
$page_object = get_queried_object();
$page_id  = get_queried_object_id(); // Get current page id

$args = array(
    'sort_order' => 'ASC',
    'sort_column' => 'post_title',
    'hierarchical' => 1,
    'exclude' => '',
    'include' => $page_id,
    'meta_key' => '',
    'meta_value' => '',
    'authors' => '',
    'child_of' => 0,
    'parent' => -1,
    'exclude_tree' => '',
    'number' => '',
    'offset' => 0,
    'post_type' => 'page',
    'post_status' => 'publish'
); 
$pages = get_pages($args);

$parentID = $pages[0]->post_parent; // Get current page parent id

This will gives you current page parent id, not top-level id $parentID = $pages[0]->post_parent;

share|improve this answer
    
Excellent thumbs up to you :) –  Mr.Happy May 7 at 10:12

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.