WordPress.org

Ready to get started?Download WordPress

Codex

Attention Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/locate template

Description

Retrieve the name of the highest priority template file that exists, optionally loading that file.

Searches STYLESHEETPATH before TEMPLATEPATH, so themes which inherit from a parent can overload one file.

Usage

<?php locate_template$template_names$load$require_once ?>

Parameters

$template_names
(array) (required) Array of template files to search for, in priority order. (Requires file extension.)
Default: None
$load
(boolean) (optional) If true, the template file will be loaded, if it is found.
Default: false
$require_once
(boolean) (optional) If true, the template file will be loaded with the php require_once function. If false, the template file will be loaded with the php require function. This parameter has no effect if $load is false.
Default: true

Return Values

(string) 
The template filename, if one is located, an empty string, if not.

Examples

Load a specific template part based on the current pagename:

if (locate_template('content-' . $pageName . '.php') != '') {
	// yep, load the page template
	get_template_part('content', $pageName);
} else {
	// nope, load the content
	the_content();
}

Load a custom RSS feed template from the currently active theme if one exists, or from the plugin's own template directory as a fallback. (A simplified example from the "BitTorrent My Blog" plugin.)

class WP_BitTorrent {

    public function __construct () {
        add_action('init', array($this, 'registerRewrites'));
    }

    public function registerRewrites () {
        // Recognize 'torrent' RSS feeds
        add_feed('torrent', array($this, 'dispatchTorrentFeed'));
    }

    public function dispatchTorrentFeed () {
        $themed = locate_template('rss-torrent.php');
        if (!empty($themed)) {
            // The current theme has a template file called "rss-torrent.php"
            load_template($themed);
        } else {
            // The current theme did not provide its own torrent feed template,
            // so load the default one packaged with the plugin.
            load_template(dirname(__FILE__) . '/templates/rss-torrent.php');
        }
    }

}

Notes

Change Log

Since: 2.7.0

Source File

locate_template() is located in wp-includes/template.php.

Related

See also index of Function Reference and index of Template Tags.
This page is marked as incomplete. You can help Codex by expanding it.