Skip to content

Instantly share code, notes, and snippets.

@markhowellsmead
Last active September 25, 2021 22:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markhowellsmead/81914dcf2512b7b88d1c2fa4738b955c to your computer and use it in GitHub Desktop.
Save markhowellsmead/81914dcf2512b7b88d1c2fa4738b955c to your computer and use it in GitHub Desktop.
Alternative to WordPress' get_template_part function , which allows you to pass data to the template part. Requires PHP 7+ because of the coalescing operator. Info at https://permanenttourist.ch/2019/10/passing-data-to-wordpress-template-parts/
<?php
public function getTemplatePart(string $file_path, ...$arguments)
{
$data = [];
// Array containing possible paths to the template part
$parts = (array) $file_path;
if (is_array($arguments)) {
// Find an array in $attributes and use it as $data in the
// included template part
foreach ($arguments as $attribute) {
if (is_array($attribute)) {
$data = $attribute;
break;
}
}
// If the first function attribute after $file_path is a string,
// prepend the alternative (e.g. post type) name to the paths array
// e.g. [partials/excerpt-customposttype, partials/excerpt]
if (is_string($arguments[0] ?? null)) {
array_unshift($parts, $file_path.'-'.$arguments[0]);
}
}
// Make sure that each possible file path is suffixed with .php
if (!empty($parts)) {
foreach ($parts as &$file) {
if (false === strpos($file, '.php')) {
$file .= '.php';
}
}
if (!empty($template = locate_template($parts))) {
require(locate_template($parts));
}
}
}
<?php
foreach($my_authors as $author){
sht_theme()->getTemplatePart('partials/meta/author_card', [
'author' => $author
]);
}
// OR
foreach($my_authors as $author){
sht_theme()->getTemplatePart('partials/meta/author_card', get_post_type(), [
'author' => $author
]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment