PHPackages                             wpsmith/templates - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Templating &amp; Views](/categories/templating)
4. /
5. wpsmith/templates

ActiveLibrary[Templating &amp; Views](/categories/templating)

wpsmith/templates
=================

WordPress templates.

1.0.0(5y ago)01433GPL-2.0+PHPPHP &gt;=7.0.0

Since Jun 12Pushed 5y ago1 watchersCompare

[ Source](https://github.com/wpsmith/Templates)[ Packagist](https://packagist.org/packages/wpsmith/templates)[ Docs](https://github.com/wpsmith/Templates)[ RSS](/packages/wpsmith-templates/feed)WikiDiscussions master Synced 4d ago

READMEChangelogDependencies (1)Versions (5)Used By (3)

Template Loader
===============

[](#template-loader)

[![Code Climate](https://camo.githubusercontent.com/a74fa2aaf1338c5d5213a646eb89bbc03253e6da06fe0a04718d488c6602e449/68747470733a2f2f636f6465636c696d6174652e636f6d2f6769746875622f7770736d6974682f54656d706c617465732f6261646765732f6770612e737667)](https://codeclimate.com/github/wpsmith/Templates)

A class to copy into your WordPress plugin, to allow loading template parts with fallback through the child theme &gt; parent theme &gt; plugin.

This is largely based on Gary Jones's [Gamajo\_Template\_Loader](https://github.com/GaryJones/Gamajo-Template-Loader/). The main difference between Gary's version and this one is twofold:

1. I didn't want to extend the class for each and every plugin I created...call me lazy.
2. I didn't want to load the template parts automatically.

Description
-----------

[](#description)

Easy Digital Downloads, WooCommerce, and Events Calendar plugins, amongst others, allow you to add files to your theme to override the default templates that come with the plugin. As a developer, adding this convenience in to your own plugin can be a little tricky.

The `get_template_part()` function in WordPress was never really designed with plugins in mind, since it relies on `locate_template()` which only checks child and parent themes. So we can add in a final fallback that uses the templates in the plugin, we have to use a custom `locate_template()` function, and a custom `get_template_part()` function. The solution here just wraps them up as a class for convenience.

Installation
------------

[](#installation)

This isn't a WordPress plugin on its own, so the usual instructions don't apply. Instead:

### Manually install class

[](#manually-install-class)

1. Copy [`Templates/src/TemplateLoader.php`](TemplateLoader.php) for basic usage

or:

1. Copy [`Templates/src/TemplateLoaderData.php`](TemplateLoaderData.php) and `Templates/src/TemplateLoader.php`\](TemplateLoader.php) into your plugin. It can be into a file in the plugin root, or better, an `includes` directory.

or:

### Install class via Composer

[](#install-class-via-composer)

1. Tell Composer to install this class as a dependency: `composer require wpsmith/templates`
2. Recommended: Install the Mozart package: `composer require coenjacobs/mozart --dev` and [configure it](https://github.com/coenjacobs/mozart#configuration).
3. The class is now renamed to use your own prefix, to prevent collisions with other plugins bundling this class.

Implementation &amp; Usage
--------------------------

[](#implementation--usage)

Unlike Gamajo's [Gamajo\_Template\_Loader](https://github.com/GaryJones/Gamajo-Template-Loader#implement-class), you do not have to implement a new class.

Assuming...

```
// Set at the root folder of your plugin (e.g., wp-content/plugins/yourplugin/yourplugin.php).
// Defines YOUR_PLUGIN_DIRNAME as yourplugin.
define( 'YOUR_PLUGIN_DIRNAME', dirname( __FILE__ ) );
```

### Initialization

[](#initialization)

We can initialize `TemplateLoader`:

```
// Create the loader with my prefix and directory.
// This assumes:
//  - plugin templates are found in the plugin folder: wp-content/plugins/yourplugin/templates/...
//  - theme templates are found in the plugin folder: wp-content/themes/yourtheme/templates/...
$template_loader = new TemplateLoader( [
    'prefix'           => 'wps',
    'plugin_directory' => YOUR_PLUGIN_DIRNAME,
] );
```

Or,

```
// Create the loader with all the parts.
// This declares:
//  - plugin templates are found in the plugin folder: wp-content/plugins/yourplugin/templates/...
//  - theme templates are found in the plugin folder: wp-content/themes/yourtheme/templates/yourplugin/...
$template_loader = new TemplateLoader( [
    'prefix'                   => 'wps',
    'theme_template_directory' => 'templates/yourplugin',
    'templates_directory'      => 'templates',
    'plugin_directory'         => WPS_PLUGIN_DIRNAME,
] );
```

You could utilize a template loader helper which will always return the same template loader:

```
/**
 * Gets the plugin template loader.
 *
 * @return \WPS\WP\Templates\TemplateLoader
 */
function yourprefix_get_template_loader() {
	static $loader;
	if ( $loader === null ) {
		$loader = new \WPS\WP\Templates\TemplateLoader( [
			'prefix'                   => 'wps',
            'theme_template_directory' => 'templates/yourplugin',
            'templates_directory'      => 'templates',
            'plugin_directory'         => WPS_PLUGIN_DIRNAME,
		) );
	}

	return $loader;
}
```

Finally, you can use it for configuration purposes too.

```
/**
 * Gets a configuration file as a data array.
 *
 * @return array
 */
function yourprefix_get_config( $config ) {
    static $loader;

    if ( $loader === null ) {
        $loader = new TemplateLoader( [
            'filter_prefix'            => 'wps',
            'theme_template_directory' => 'config',
            'templates_directory'      => 'config',
            'plugin_directory'         => WPS_PLUGIN_DIRNAME,
        ] );
    }

    $template = $loader->get_template_part( 'config', $config );

    $data = array();
    if ( is_readable( $template ) ) {
        $data = require $template;
    }

    return (array) $data;
}
```

### Usage

[](#usage)

- Use it to call the `load_template_part()` method. This could be within a shortcode callback, or something you want theme developers to include in their files.

    ```
    $template_loader->load_template_part( 'recipe' );
    ```
- Use it to call the `get_template_part()` method. This could be within a shortcode callback, or something you want theme developers to include in their files.

    ```
    // This will return the path to the particular template part.
    $template_loader->get_template_part( 'recipe' );

    // This will load the particular template part.
    $template_loader->get_template_part( 'recipe', null, true );
    ```
- If you want to pass data to the template, call the `set_template_data()` method with an array before calling `get_template_part()`. `set_template_data()` returns the loader object to allow for method chaining.

    ```
    $data = [ 'foo' => 'bar', 'baz' => 'boom' ];
    $template_loader
      ->set_template_data( $data );
      ->get_template_part( 'recipe' );
    ```

    The value of `bar` is now available inside the recipe template as `$wps_data->foo`.

    If you wish to use a different variable name, add a second parameter to `set_template_data()`:

    ```
    $data = array( 'foo' => 'bar', 'baz' => 'boom' );
    $meal_planner_template_loader
      ->set_template_data( $data, 'context' )
      ->get_template_part( 'recipe', 'ingredients' );
    ```

    The value of `bar` is now available inside the recipe template as `$context->foo`.

    This will try to load up:

    - Theme Templates:
        - `wp-content/themes/my-theme/meal-planner/recipe-ingredients.php`
        - `wp-content/themes/my-theme/meal-planner/ingredients.php`
        - `wp-content/themes/my-theme/meal-planner/recipe.php`
    - Plugin Templates:
        - `wp-content/plugins/meal-planner/templates/recipe-ingredients.php`
        - `wp-content/plugins/meal-planner/templates/ingredients.php`.
        - `wp-content/plugins/meal-planner/templates/recipe.php`.

Change Log
----------

[](#change-log)

See the [change log](CHANGELOG.md).

License
-------

[](#license)

[GPL 2.0 or later](LICENSE).

Contributions
-------------

[](#contributions)

Contributions are welcome - fork, fix and send pull requests against the `develop` branch please.

Credits
-------

[](#credits)

Based upon [Gary Jones's](https://garyjones.io) [Gamajo\_Template\_Loader](https://github.com/GaryJones/Gamajo-Template-Loader/)Built by [Travis Smith](https://twitter.com/wp_smith)
Copyright 2013-2020 [Travis Smith](https://wpsmith.net)

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity61

Established project with proven stability

 Bus Factor1

Top contributor holds 81.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~351 days

Total

4

Last Release

1839d ago

Major Versions

0.0.3 → 1.0.02021-05-01

PHP version history (3 changes)0.0.1PHP &gt;=5.2.4

0.0.2PHP &gt;=5.6.0

0.0.3PHP &gt;=7.0.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/46adebc3eebe7494dba592e75ac8f8572222050648b0283515b4a5896648d846?d=identicon)[wpsmith](/maintainers/wpsmith)

---

Top Contributors

[![wpsmith](https://avatars.githubusercontent.com/u/817366?v=4)](https://github.com/wpsmith "wpsmith (13 commits)")[![wpsmithtwc](https://avatars.githubusercontent.com/u/15801496?v=4)](https://github.com/wpsmithtwc "wpsmithtwc (3 commits)")

---

Tags

wordpresstemplates

### Embed Badge

![Health badge](/badges/wpsmith-templates/health.svg)

```
[![Health](https://phpackages.com/badges/wpsmith-templates/health.svg)](https://phpackages.com/packages/wpsmith-templates)
```

###  Alternatives

[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[gamajo/template-loader

A class for your WordPress plugin, to allow loading template parts with fallback through the child theme &gt; parent theme &gt; plugin

29647.0k5](/packages/gamajo-template-loader)[hexbit/sage-woocommerce

Woocommerce support for sage 10

257.0k](/packages/hexbit-sage-woocommerce)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
