0

I'm working on a function.php file for a new theme system. I need to know how to make a custom template executable through a URL. So if someone were to go to http://website.com/my-custom-template/ how can I make it so that page that loads reads from the template my-custom-template.php in the themes folder?

2

You can use wordpress templates to load for a particular page. just create a template file with any name ( place template definition in file i.e commented code to declare a template) and select it as a template while adding a page. in this way file will be loaded automatically for page and you can use that template for other pages also. add following code at top of you file

<?php
/**
 * Template Name: My custom template
 *
?>
0

This is a bit tricky, and while possible, I'd recommend not doing this. It's not how WordPress is designed to operate, so depending on what's going on in this template, you may have lots of little issues to clean up. I would instead suggest researching ways to provide an interface for generating actual pages in the database to go with corresponding template files.

That said, here's an example of how you might load a file based on the requested slug. Here we hook the template_redirect action and first check if the request resulted in a 404 (nothing matching the request in the database). If so, we try to find a template with matching slug, and load that if it's found. Note the 200 header that's sent before the template is loaded, otherwise WordPress will send a 404 for the request.

function wpa_template_redirect(){
    global $wp_query;
    if( $wp_query->is_404 ){
        if( $located = locate_template( $wp_query->query_vars['name'] . '.php' ) ){
            header( "HTTP/1.0 200 OK" );
            load_template( $located );
            exit;
        }
    }
}
add_action( 'template_redirect', 'wpa_template_redirect' );

Now if this template file contains any template tags that rely on the presence of a query object (which will exist in any case where something was found for the request), you'll get errors. The one glaring issue you'll note is that the page's title will be "Page not found".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.