Prevent 404 and serve custom template for custom URL

Got it! But this is a dirty thing. As it won’t take care of pagination and underlying queries. If you need a bit more of WordPress’ logic behind that custom route, please check the answer linked in the comments. But if you just need to serve one static page, this probably is a good starting point:

add_action('template_include', 'template_suggestions');
function template_suggestions($template) {

  global $wp;

  $current_slug = $wp->request;

  $foobar_template = locate_template(['foobar.php']);

  if ($current_slug == 'foobar' && $foobar_template != '') {

    // Prevent 404.
    status_header(200);

    return $foobar_template;
  }

  return $template;
}

Source Don’t use template_redirect to load an alternative template file


Since I use Yoast I had to use wpseo_title instead of document_title_parts or pre_get_document_title to set the title accordingly.

add_filter('wpseo_title', 'template_suggestions_titles', 10, 1);
function template_suggestions_titles() {

  global $wp;

  $current_slug = $wp->request;

  if ($current_slug == 'foobar') {

    return 'Foobar';
  }
}