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

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), '/');
  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.


The init action isn't appropriate for what you're trying to achieve. You should be using the template_include filter instead. You'd combine this with get_query_var to retrieve the URL params to check what template needs to be loaded. Here are the links:

  • https://codex.wordpress.org/Plugin_API/Filter_Reference/template_include
  • https://codex.wordpress.org/Function_Reference/get_query_var

Code:

add_filter( 'template_include', 'portfolio_page_template', 99 );

function portfolio_page_template( $template ) {

    if ( is_page( 'portfolio' )  ) {
        $new_template = locate_template( array( 'portfolio-page-template.php' ) );
        if ( '' != $new_template ) {
            return $new_template ;
        }
    }

    return $template;
}

The WordPress-way to do this is with page-templates. https://developer.wordpress.org/themes/template-files-section/page-template-files/

You only need a code for the WordPress template. In your WordPress theme you can create a page template and rename it to

page-id.php

That particular page will automatically pick it up and use the template.

For example if your page has an id of 5874 you'll name the template as page-5784.php

You can also name the template based on the page slug. For example if the page slug is hello-world then the template name will be page-hello-world.php

Also see: - https://developer.wordpress.org/files/2014/10/template-hierarchy.png