Use a template file for a specific url without creating a page

I wonder if its possible to use a template file for a specific url without having to create a page for that template.

This is my simplified problem:

I have created a page in WP with some link content that points to a specific url with some trailing form data: (mysite.com/retail/?a=test&b=1234).

I want that url (retail) to automatically use my template file template-retail.php that I have in the child theme directory, without having to create a page named ”retail” & select the template page from there. There is only external content in the template-retail.php file, nothing from WordPress itself.

Is this possible?

4

You can just look at url, load the file and exit.

That can be done when WordPress loaded its environment, e.g. on 'init'.

add_action('init', function() {
  $url_path = trim(parse_url(add_query_arg(array()), PHP_URL_PATH), "https://wordpress.stackexchange.com/");
  if ( $url_path === 'retail' ) {
     // load the file if exists
     $load = locate_template('template-retail.php', true);
     if ($load) {
        exit(); // just exit if template was found and loaded
     }
  }
});

Note that doing so a real page with slug “retail” can never be used.

This is pretty easy, but also hardcoded, so if you need this for a single page it’s fine. If you need to control more urls, have a look to the solution proposed in this answer.

Leave a Comment