Skip to content

Instantly share code, notes, and snippets.

@kellenmace
Created September 28, 2018 11:12
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 kellenmace/386a5a7c79e8a2eca5e9c2641425fa4c to your computer and use it in GitHub Desktop.
Save kellenmace/386a5a7c79e8a2eca5e9c2641425fa4c to your computer and use it in GitHub Desktop.
WordPress - get template part path
<?php
/**
* Get template part path. This function is identical to WP's
* get_template_part(), except that it doesn't load the template -
* just returns it so that it can be required elsewhere and have
* access to variables in the local scope.
*
* Example usage:
* $template_data = 'make this variable available in template part';
* require get_template_part_path( 'template-parts/content', 'some-template-part' );
*
* @param string $slug The slug name for the generic template.
* @param string $name The name of the specialised template.
* @return string The template part path.
*/
function get_template_part_path( $slug, $name = null ) {
/**
* 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.
*/
do_action( "get_template_part_{$slug}", $slug, $name );
$templates = array();
$name = (string) $name;
if ( '' !== $name ) {
$templates[] = "{$slug}-{$name}.php";
}
$templates[] = "{$slug}.php";
return locate_template( $templates );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment