Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Custom wrapper for require() instead of get_template_part()

Usage in templates

  1. Load template your-theme/templates/cards/post.php. Please note that global variable will be accessible in the template.
get_partial( 'templates/cards/post' );
  1. Load template your-theme/templates/cards/post.php and pass a local variable.
$var = 'Hello world';

get_partial( 'templates/cards/post', compact( 'var') );

In template, just use $var as normal:

echo $var;
  1. Load template your-theme/templates/cards/post.php and pass multiple local variables.
$var_one = 'Hello';
$var_two = 'World';

get_partial( 'templates/cards/post', compact( 'var_one', 'var_two' ) );

In template, just use $var as normal:

echo $var_one, ' ', $var_two;
<?php
define( 'THEME_PATH', __DIR__ );
/**
* A faster alternative to native get_template_part() function.
*
* @param string $template
* @param mixed $data
*
* @return void
*/
function get_partial( string $template, $data = null ): void
{
if ( $data && is_array( $data ) ) {
extract( $data, EXTR_OVERWRITE );
}
require THEME_PATH . "/{$template}.php";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment