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

Lets say on my WordPress website I navigate to:


In this case I am looking at a post in a CPT called News.

What I want to do is get the page ID thats closest to that URL. I know the closest page ID can be found at:


So how do I loop back over my URL to find the closest page and then how do I get the ID of that page?

share|improve this question
By closest do you mean a news CPT with post ID closest to '17'? – Stephen Harris Jun 29 '12 at 14:01
No. I'm after a Page ID here nothing to do with posts. The closest page in my example is /media-centre/news/, in this example I would be after the Page ID of news. – Brady Jun 29 '12 at 14:04

You should be able to get the current url from $url = add_query_arg().

Then assuming, the structure: www.example.com/page/subpage/news/ID/post you can use preg_match to extract /page/subpage/news. Then it would be simple matter of using get_page_by_path();.

If that fails you can then check /page/subpage/ and finally /page.

share|improve this answer
up vote 1 down vote accepted

Got there myself with the aid from Stephen Harris and some PHP help over at SO.

$page = get_closest_page();

// echo $page->ID;

function get_closest_page( $url = false )
    global $wp;

    if( ! $url )
        $url = $wp->request;

    $page = get_page_by_path( $url );

    if( $page )
        return $page;

    $url = dirname( $url );

    return get_closest_page( $url );
share|improve this answer

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.