Programmatically add a custom page/path/url/route to WordPress

The idea is just to programmatically create a path/url in a plugin for a WordPress site (like, “[mysite]/mypath”), and then load an arbitrary html or php file. In case anyone else is looking for something similar, this works for me (in my main plugin function file):

register_activation_hook(__FILE__, 'myplugin_activate'); 
function myplugin_activate () {
  create_custom_page('mytestpath');
}

function create_custom_page($page_name) {
  $pageExists = false;
  $pages = get_pages();     
  foreach ($pages as $page) { 
    if ($page->post_name == $page_name) {
      $pageExists = true;
      break;
    }
  }
  if (!$pageExists) {
    wp_insert_post ([
        'post_type' =>'page',        
        'post_name' => $page_name,
        'post_status' => 'publish',
    ]);
  }
}
// End Plugin Activation


//Start Catching URL
add_filter( 'page_template', 'catch_mypath' );
function catch_mypath( $page_template ) {
    if ( is_page( 'mytestpath' ) ) {
        $page_template = __DIR__.'/mypage.html';
    }
    return $page_template;
}

References: