Skip to content

Instantly share code, notes, and snippets.

@mcaskill
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcaskill/ef92643dc27318f36753 to your computer and use it in GitHub Desktop.
Save mcaskill/ef92643dc27318f36753 to your computer and use it in GitHub Desktop.
WordPress : Load a template part into a template and pass scoped variables
<?php
/**
* Load a template part into a template
*
* Makes it easy for a theme to reuse sections of code in a easy to overload way
* for child themes.
*
* Includes the named template part for a theme or if a name is specified then a
* specialised part will be included. If the theme contains no {slug}.php file
* then no template will be included.
*
* The template is included using require, not require_once, so you may include the
* same template part multiple times.
*
* For the $name parameter, if the file is called "{slug}-special.php" then specify
* "special".
*
* For the $data parameter represents variables to be passed to the view
* without having to rely on the global scope.
*
* @link https://core.trac.wordpress.org/ticket/21673
*
* @param mixed|string $slug The slug name for the generic template.
* @param string $name The name of the specialised template.
* @param array $data Variables to be pass along to the specialized template.
*/
function get_template_view( $slug, $name = null, $data = [] )
{
$defaults = [
'slug' => '',
'name' => null,
'data' => []
];
$args = null;
$params = func_get_args();
foreach ( $params as $param => $value ) {
if ( is_array( $value ) && isset( $value['slug'] ) ) {
$args = $value;
break;
}
}
if ( is_null( $args ) && is_string( func_get_arg( 0 ) ) ) {
$args = $params;
}
else {
return false;
}
$args = wp_parse_args( $args, $defaults );
extract( $args, EXTR_SKIP, '__' );
unset( $args, $params );
/**
* Fires before the specified template part file is loaded.
*
* The dynamic portion of the hook name, `$slug`, refers to the slug name
* for the generic template part.
*
* @since 3.0.0
*
* @param string $__slug The slug name for the generic template.
* @param string $__name The name of the specialized template.
* @param array $__data Variables to be pass along to the specialized template.
*/
do_action( "get_template_part_{$__slug}", $__slug, $__name, $__data );
$__templates = [];
$__name = (string) $__name;
if ( '' !== $__name ) {
$__templates[] = "{$__slug}-{$__name}.php";
}
$__templates[] = "{$__slug}.php";
$__template_name = locate_template( $__templates, false, false );
if ( '' != $__template_name ) {
unset( $__templates, $__slug, $__name );
if ( ! empty( $__data ) && is_array( $__data ) ) {
extract( $__data, EXTR_SKIP );
}
include( $__template_name );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment