Skip to content

Instantly share code, notes, and snippets.

@alexmccabe
Last active September 11, 2018 08:51
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 alexmccabe/37370eda7d6eae7e6fa79b2c73c93e82 to your computer and use it in GitHub Desktop.
Save alexmccabe/37370eda7d6eae7e6fa79b2c73c93e82 to your computer and use it in GitHub Desktop.
After getting incredibly frustrated with the included get_template_part function in Wordpress, I decided to write my own that makes getting templates much easier. This function allows you to omit the '.php' extension, and also pass down data to the included file. You can just add this anywhere in your `functions.php` file, or anywhere else that …
<?php
if (! function_exists('better_get_template_part') {
/**
* A better way of getting a Wordpress Template Part.
* This function allows you to to omit the '.php' extension, and also pass
* data to the included file.
*
* The data in the array is extracted into variables for use on the
* template directly.
*
* @param string $filename Path to file, starting from '/template-parts'
* @param array $data Data to be included in the template
* @param boolean $includeOnce Only include the template once. Defaults to false
* @return void
*/
function better_get_template_part($filename, array $data = [], $includeOnce = false)
{
$name = str_replace('_', '-', $filename);
$templateURL = get_template_directory() . '/template-parts';
$fullURL = $templateURL . $name;
$pathinfo = pathinfo($fullURL);
if (!isset($pathinfo['extension'])) {
$fullURL .= '.php';
}
if (!file_exists($fullURL)) {
return false;
}
extract($data);
if ($includeOnce) {
include_once($fullURL);
} else {
include($fullURL);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment