Los archivos de plantillas son muy comunes en los temas y se usan mucho en los temas hijos. Por ejemplo, si un usuario quiere modificar el diseño de las páginas de su sitio, puede simplemente copiar `page.php` desde su tema principal a un tema hijo, modificar la estructura HTML, y los cambios se reflejarán en el sitio. Aunque es bien sabido que los archivos de plantillas como `page.php` también pueden ser creados para plugins, siento que la mayoría de los desarrolladores tienden a evitar construirlos debido a la complejidad de crear un cargador de plantillas en un plugin. Primero, me gustaría explicarte la lógica de cómo funciona un cargador de archivos de plantillas; segundo, voy a mostrarte un ejemplo real; y tercero, te voy a mostrar lo fácil que es ahora construir un cargador de plantillas en tu plugin.

El concepto de un cargador de plantillas es bastante simple:

  1. Determinar el nombre del archivo que se va a cargar.
  2. Determinar las ubicaciones donde buscar el archivo y el orden en que se debe buscar en cada una.
  3. Buscar el archivo en cada ubicación.
  4. Cargar el archivo y dejar de buscar tan pronto como se encuentre.
  5. Recurrir a una plantilla predeterminada si el archivo solicitado nunca se encuentra.

Al crear un cargador de plantillas en un plugin, el desarrollador usualmente crea una carpeta principal de plantillas (el nombre puede variar) que existe dentro del plugin y que contendrá todos los archivos de plantillas disponibles. Estos archivos luego pueden ser copiados a una carpeta con un nombre específico en el tema activo para ser modificados. Si un archivo de la carpeta de plantillas del plugin existe dentro del tema, se cargará en lugar de la versión predeterminada del plugin.

Los cargadores de archivos de plantillas como este se utilizan en muchos plugins a gran escala para proporcionar mayor flexibilidad y mejor control a los usuarios avanzados que desean adaptar la salida del plugin a sus necesidades específicas. Algunos ejemplos de plugins que usan cargadores de archivos de plantillas son:

  • Digital Downloads
  • WooCommerce
  • bbPress
  • buddyPress

Let’s look at a quick example of what a template file loader looks like in a plugin. We will use Restrict Content Pro (RCP) for this example.

RCP has several template files for the registration form, the login form, and the user’s profile editor form. The login form template, as an example, looks like this:

<!--?php global $rcp_login_form_args; ?-->
<!--?php if( ! is_user_logged_in() ) : ?-->

&nbsp;

<form id="rcp_login_form" class="rcp_form" action="&lt;?php echo esc_url( rcp_get_current_url() ); ?&gt;&lt;p&gt;" method="POST">
<fieldset class="rcp_login_data"><label for="rcp_user_Login"><!--?php _e( 'Username', 'rcp' ); ?--></label>
<input id="rcp_user_login" class="required" name="rcp_user_login" type="text" />

<label for="rcp_user_pass"><!--?php _e( 'Password', 'rcp' ); ?--></label>
<input id="rcp_user_pass" class="required" name="rcp_user_pass" type="password" />

<label for="rcp_user_remember"><!--?php _e( 'Remember', 'rcp' ); ?--></label>
<input id="rcp_user_remember" name="rcp_user_remember" type="checkbox" value="1" />
<p class="rcp_lost_password"></p>
<input name="rcp_action" type="hidden" value="login" />
<input name="rcp_redirect" type="hidden" value="&quot;&lt;?php" />"/&gt;
<input name="rcp_login_nonce" type="hidden" value="&quot;&lt;?php" />"/&gt;
<input id="rcp_login_submit" type="submit" value="Login" /></fieldset>
</form>&nbsp;
<div class="rcp_logged_in"></div>
<!--?php endif; ?-->

This file is mostly straight HTML with a little bit of PHP. A pretty standard template file.

Restrict Content Pro loads this file through a short code, and when that happens, it looks like this:

rcp_get_template_part( ‘login’ );
The rcp_get_template_part() takes care of searching each of the possible locations for a file called login.php and then loading the file if it exists.

The rcp_get_template_part() function looks like this:

/**
* Retrieves a template part
*
* @since v1.5
*
* Taken from bbPress
*
* @param string $slug
* @param string $name Optional. Default null
*
* @uses rcp_locate_template()
* @uses load_template()
* @uses get_template_part()
*/
function rcp_get_template_part( $slug, $name = null, $load = true ) {
// Execute code for this part
do_action( ‘get_template_part_’ . $slug, $slug, $name );

// Setup possible parts
$templates = array();
if ( isset( $name ) )
$templates[] = $slug . ‘-‘ . $name . ‘.php’;
$templates[] = $slug . ‘.php’;

// Allow template parts to be filtered
$templates = apply_filters( ‘rcp_get_template_part’, $templates, $slug, $name );

// Return the part that is found
return rcp_locate_template( $templates, $load, false );
}
This function does four things:

Fires a do_action() call so that other plugins can hook into the load process of specific template files.
Determines the names of the template files to look for.
Passes the template file names through a filter so other plugins can force it to look for additional or different template files.
Fires rcp_locate_template(), which performs the actual file lookups.
Before we have a final picture of how this works, we need to look at rcp_locate_template():

/**
* Retrieve the name of the highest priority template file that exists.
*
* Searches in the STYLESHEETPATH before TEMPLATEPATH so that themes which
* inherit from a parent theme can just overload one file. If the template is
* not found in either of those, it looks in the theme-compat folder last.
*
* Taken from bbPress
*
* @since v1.5
*
* @param string|array $template_names Template file(s) to search for, in order.
* @param bool $load If true the template file will be loaded if it is found.
* @param bool $require_once Whether to require_once or require. Default true.
* Has no effect if $load is false.
* @return string The template filename if one is located.
*/
function rcp_locate_template( $template_names, $load = false, $require_once = true ) {
// No file found yet
$located = false;

// Try to find a template file
foreach ( (array) $template_names as $template_name ) {

// Continue if template is empty
if ( empty( $template_name ) )
continue;

// Trim off any slashes from the template name
$template_name = ltrim( $template_name, ‘/’ );

// Check child theme first
if ( file_exists( trailingslashit( get_stylesheet_directory() ) . ‘rcp/’ . $template_name ) ) {
$located = trailingslashit( get_stylesheet_directory() ) . ‘rcp/’ . $template_name;
break;

// Check parent theme next
} elseif ( file_exists( trailingslashit( get_template_directory() ) . ‘rcp/’ . $template_name ) ) {
$located = trailingslashit( get_template_directory() ) . ‘rcp/’ . $template_name;
break;

// Check theme compatibility last
} elseif ( file_exists( trailingslashit( rcp_get_templates_dir() ) . $template_name ) ) {
$located = trailingslashit( rcp_get_templates_dir() ) . $template_name;
break;
}
}

if ( ( true == $load ) && ! empty( $located ) )
load_template( $located, $require_once );

return $located;
}
This function takes an array of template file names, such as array( ‘login.php’, ‘login-form.php’ ), loops through the list and searches in each of the possible locations for the files. As soon as it finds a matching file, it does one of two things:

If the third parameter, $load, is true, the file is loaded with the core WordPress function load_template()
If $load is false, it returns the absolute path to the file
For Restrict Content Pro, the locations rcp_locate_template() looks are (in this order):

wp-content/themes/CHILD_THEME/rcp/{filename}
wp-content/themes/PARENT_THEME/rcp/{filename}
wp-content/plugins/restrict-content-pro/templates/{filename}
That’s the entire process. While it is not a ton of code, it is something that can be intimidating to write from scratch (note, I took most of my code straight from bbPress, thanks JJJ!). If you are not writing a large plugin, it can be difficult to justify spending a lot of time on a system like this, which leads me into the next part of this tutorial.

Gary Jones recently released a Template Loader class that does most of the heavy lifting for you. The class is based on the template loader built into Easy Digital Downloads (which was based off of the one in bbPress), so it works nearly identically to the methods described above for Restrict Content Pro, except it takes an OOP approach.

I’m not going to walk you through the class, but I am going to show you a quick example of how to use it so that you can easily build template file loaders into your own plugins.

First, you will copy the main Gamajo_Template_Loader class into a new file in your plugin.

Second, you will write a new class that extends Gamajo_Template_Loader, like this:

* Template loader for PW Sample Plugin.
*
* Only need to specify class properties here.
*
*/
class PW_Template_Loader extends Gamajo_Template_Loader {

/**
* Prefix for filter names.
*
* @since 1.0.0
* @type string
*/
protected $filter_prefix = ‘pw’;

/**
* Directory name where custom templates for this plugin should be found in the theme.
*
* @since 1.0.0
* @type string
*/
protected $theme_template_directory = ‘pw-templates’;

/**
* Reference to the root directory path of this plugin.
*
* @since 1.0.0
* @type string
*/
protected $plugin_directory = PW_SAMPLE_PLUGIN_DIR;

}
This class simply defines the prefix for filters, the name of the directory that files will be searched for in from the current theme, and also the plugin’s own directory.

Third, you include both of these class files into your plugin and instantiate the sub class:

When put in our short code, it looks like this:

function pw_sample_shortcode() {

$templates = new PW_Template_Loader;

ob_start();
$templates->get_template_part( ‘content’, ‘header’ );
$templates->get_template_part( ‘content’, ‘middle’ );
$templates->get_template_part( ‘content’, ‘footer’ );
return ob_get_clean();

}
add_shortcode( ‘pw_sample’, ‘pw_sample_shortcode’ );
Note that an output buffer is used because short codes, in order to work correctly, must always return their content, and the template loader includes the files directly.

To help demonstrate exactly how to use this class, I’ve written a sample plugin that can be viewed and downloaded from Github.

Having template files available for advanced users of your plugin can dramatically improve the flexibility of your plugin. I would absolutely recommend implementing them in any and all decently large plugins that include output on the front end of the site.