How to Check if a Page Exists by URL?

I need to display certain content depending on whether or not a page URL exists. I don’t want to check by title, because certain pages will have the same title, and just different parent pages.

For example one page may be:

  1. http://example.com/analysis/firstNamelastName
  2. http://example.com/exercise/firstNamelastName

I just need to know if one of these URL exists or not.

1
1

You could make a list of paths to check…

$page_paths = array(
    'analysis/firstNamelastName',
    'exercise/firstNamelastName'
);

Then check if there’s a page object for each of the page paths.

foreach( $page_paths as $page_path ) {

    echo '<code>' . $page_path . '</code> ' . PHP_EOL;

    if( ! $page = get_page_by_path( $page_path ) ){
        echo 'Does not exist.' . PHP_EOL;
    } else{
        echo 'Exists and resolves to: <code>' . get_permalink( $page->ID ) . '</code>' . PHP_EOL;
    }  

}

You can actually use get_page_by_path(); for Post Types other than page. See the third parameter.

Leave a Comment