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?

  • 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. – Scott 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.


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 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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