How to Check if a Page Exists by URL?

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