• Stars
    star
    280
  • Rank 147,492 (Top 3 %)
  • Language
    PHP
  • License
    GNU General Publi...
  • Created almost 11 years ago
  • Updated about 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

Gamajo Template Loader

Code Climate

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

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

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

Manually install class

  1. Copy class-gamajo-template-loader.php into your plugin. It can be into a file in the plugin root, or better, an includes directory.

or:

Install class via Composer

  1. Tell Composer to install this class as a dependency: composer require gamajo/template-loader
  2. Recommended: Install the Mozart package: composer require coenjacobs/mozart --dev and configure it.
  3. The class is now renamed to use your own prefix, to prevent collisions with other plugins bundling this class.

Implement class

  1. Create a new file, such as class-your-plugin-template-loader.php, in the same directory.
  2. Create a class in that file that extends Gamajo_Template_Loader (or the new prefixed name, if you installed via Composer/Mozart). You can see the Meal Planner Template Loader example class below as a starting point if it helps.
  3. Override the class properties to suit your plugin. You could also override the get_templates_dir() method if it isn't right for you.
  4. You can now instantiate your custom template loader class, and 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.
// Template loader instantiated elsewhere, such as the main plugin file.
$meal_planner_template_loader = new Meal_Planner_Template_Loader();
  • 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.

    $meal_planner_template_loader->get_template_part( 'recipe' );
  • 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 = array( 'foo' => 'bar', 'baz' => 'boom' );
    $meal_planner_template_loader
        ->set_template_data( $data );
        ->get_template_part( 'recipe' );

    The value of bar is now available inside the recipe template as $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 wp-content/themes/my-theme/meal-planner/recipe-ingredients.php, or wp-content/themes/my-theme/meal-planner/recipe.php, then fallback to wp-content/plugins/meal-planner/templates/recipe-ingredients.php or wp-content/plugins/meal-planner/templates/recipe.php.

  • You can also pass the template loader object into the template as well:

    $template_loader = new Your_Template_Loader();
    $template_loader->set_template_data(
        array(
      	      'template_loader' => $template_loader,
      		  // Optional other data as needed.
          )
    );

    Then in the template you can use:

    $data->template_loader->get_template_part( 'recipe' );

Meal Planner Example Class

<?php
/**
 * Meal Planner
 *
 * @package   Meal_Planner
 * @author    Gary Jones
 * @link      http://example.com/meal-planner
 * @copyright 2013 Gary Jones
 * @license   GPL-2.0+
 */

if ( ! class_exists( 'Gamajo_Template_Loader' ) ) {
  require plugin_dir_path( __FILE__ ) . 'class-gamajo-template-loader.php';
}

/**
 * Template loader for Meal Planner.
 *
 * Only need to specify class properties here.
 *
 * @package Meal_Planner
 * @author  Gary Jones
 */
class Meal_Planner_Template_Loader extends Gamajo_Template_Loader {
  /**
   * Prefix for filter names.
   *
   * @since 1.0.0
   *
   * @var string
   */
  protected $filter_prefix = 'meal_planner';

  /**
   * Directory name where custom templates for this plugin should be found in the theme.
   *
   * @since 1.0.0
   *
   * @var string
   */
  protected $theme_template_directory = 'meal-planner';

  /**
   * Reference to the root directory path of this plugin.
   *
   * Can either be a defined constant, or a relative reference from where the subclass lives.
   *
   * In this case, `MEAL_PLANNER_PLUGIN_DIR` would be defined in the root plugin file as:
   *
   * ~~~
   * define( 'MEAL_PLANNER_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
   * ~~~
   *
   * @since 1.0.0
   *
   * @var string
   */
  protected $plugin_directory = MEAL_PLANNER_PLUGIN_DIR;

  /**
   * Directory name where templates are found in this plugin.
   *
   * Can either be a defined constant, or a relative reference from where the subclass lives.
   *
   * e.g. 'templates' or 'includes/templates', etc.
   *
   * @since 1.1.0
   *
   * @var string
   */
  protected $plugin_template_directory = 'templates';
}

Usage Example

The Cue plugin from AudioTheme uses this class. Starting at https://github.com/AudioTheme/cue/tree/develop/includes, it has this class in the vendor directory, then the required subclass of my class in the class-cue-template-loader.php file, which sets a few basic properties. It also has a template in https://github.com/AudioTheme/cue/tree/develop/templates.

If you wanted the playlist to have different markup for your theme, you'd copy templates/playlist.php to wp-content/themes/{your-active-theme}/cue/playlist.php and do whatever changes you wanted. WordPress will look for that file first, before then checking a parent theme location (if your active theme is a child theme), before falling back to the default template that comes with the Cue plugin.

Change Log

See the change log.

License

GPL 2.0 or later.

Contributions

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

Credits

Built by Gary Jones
Copyright 2013 Gary Jones

More Repositories

1

wordpress-plugin-svn-deploy

[Deprecated - use the GitHub Action from 10up instead.] Automatically deploy a WordPress plugin from local git repo to the WordPress Plugin Repostiory (SVN).
Shell
304
star
2

plugin-boilerplate

PSR-4 + PHP 7.4 WordPress plugin boilerplate.
PHP
90
star
3

genesis-header-nav

WordPress plugin that registers a menu location and displays it inside the header for a Genesis Framework child theme.
PHP
69
star
4

Simple-PHP-CSS-Minification

A set of regular expressions in PHP to minify a string of CSS.
PHP
37
star
5

move-floating-social-bar-in-genesis

Moves the Floating Social Bar plugin output from just inside the entry content to just before it.
26
star
6

genesis-js-no-js

WordPress plugin for Genesis child themes. Adds a 'no-js' body class to the front-end, and a small inline script that changes it to `js` if JavaScript is enabled. Allows for styling of elements (like potential hiding) if JavaScript is enabled.
PHP
22
star
7

accessible-menu

Making WordPress navigation menus a little more accessible.
JavaScript
20
star
8

Gamajo-Registerable

Register WordPress post types and taxonomies using object-orientated design.
PHP
18
star
9

genesis-child-theme-index

Crowdsourcing an index of all available Genesis child themes.
JavaScript
16
star
10

genesis-jetpack-infinite-scroll

Adds support for JetPack Infinite Scroll to Genesis Framework child themes.
PHP
12
star
11

wp-calendar-core

WordPress plugin, designed to be a replacement for the monstrous get_calendar() with the intention to integrate with core when stable.
PHP
12
star
12

readme-templates

Default README templates for groups of projects
9
star
13

allow-duplicate-slugs

WordPress plugin to allow duplicate slugs across different post types
PHP
8
star
14

EmailAddress

Value Object representing an email address
PHP
8
star
15

diagnosis

WordPress plugin that adds pages to the Dashboard menu with technical details about PHP, MySQL and other server details.
PHP
8
star
16

genesis-single-breadcrumbs

WordPress plugin that adds per-entry options for breadcrumbs when a Genesis child theme is active.
PHP
7
star
17

genesis-simple-sidebars-exporter

WordPress plugin that adds support for exporting settings saved from Genesis Simple Sidebars plugin, via the exporter within the Genesis Framework.
PHP
7
star
18

Core-Library-Plugin-Example

Example of a core library plugin.
PHP
6
star
19

Core-Library-Plugin-Consumer-Example

A standard WordPress plugin that has a dependency on the Core Library Plugin.
PHP
6
star
20

Genesis-Admin-Bar-Plus

Adds resource links related to the Genesis Framework to the WordPress admin bar.
PHP
5
star
21

multi-page-post-next-and-numbers

Display both Previous & Next links and numbers for multi-page posts.
PHP
5
star
22

genesis-disable-adsense-auto-ads

WordPress Plugin: Hides the references to AdSense Auto Ads in Genesis Framework 2.6.0 and above.
PHP
5
star
23

php-type-converter

Converts one resource to another (XML, JSON, Object, Array, Serialization).
PHP
5
star
24

sublime

My Sublime Text 3 User directory
Python
4
star
25

genesis-automatic-term-headline

Plugin for Genesis Framework, that automatically adds a headline to the term archive page, the same as the name of taxonomy term, if no explicit value is given.
PHP
4
star
26

dotfiles

My dotfiles
Shell
3
star
27

Gamajo-Geo-Data

Geo data retrieval library
PHP
3
star
28

PHP-Coding-Standards

Fork of the WP PHP coding standards, to add clarifications and remove ambiguities.
3
star
29

Easy-WSDL2PHP

Modified version of http://sourceforge.net/projects/easywsdl2php/
PHP
2
star
30

Gamajo-Single-Entry-Term-Body-Classes

A class to copy into your WordPress plugin, to make adding taxonomy-term HTML classes to single custom post type entries considerably easier.
PHP
2
star
31

Widget-Plugin-Boilerplate

My boilerplate set up for creating new plugins which add a widget.
PHP
2
star
32

wp-credits

Quick and dirty list from the WordPress Credits API for all credited versions
PHP
2
star
33

visual-subtitle

WordPress plugin. Allows part of a post title to be styled as a subtitle. Classic Editor only.
PHP
2
star
34

grunt-php-analyzer

php-analyzer for grunt
JavaScript
1
star
35

daterange

PHP: Display a range of dates, with consolidated time parts.
PHP
1
star
36

EDD-Content-Restriction

Content Restriction Extension for EDD
PHP
1
star
37

genesis-ignore-deprecated

Stops the Genesis Framework deprecated functions file from loading on every request, giving a small performance benefit
PHP
1
star
38

test-gpg

Just testing GPG verification
1
star
39

calendar-category

WordPress plugin. Un-registers the default Calendar widget, and registers a new one which supports showing only those posts in certain (or all) categories. Can add multiple calendar widgets – each of them set to different categories (or All Categories). The tooltip on the per-day links shows only post titles from that category, and when you click on the calendar link to bring up the day archive of posts, only posts from that category are shown.
PHP
1
star