Skip to content

Instantly share code, notes, and snippets.

@dospuntocero
Last active June 12, 2019 03:10
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 dospuntocero/f694fcb07d2a77ff3aba82e13fead90c to your computer and use it in GitHub Desktop.
Save dospuntocero/f694fcb07d2a77ff3aba82e13fead90c to your computer and use it in GitHub Desktop.
wordpress get_template_part_extra() lets you pass an array of variables to the template
<?php //called like this on other template get_template_part_extra('templates/products_accordion',[ 'key'=>'protection'] ); ?>
//inside the partial...
<h2>
<?php echo( $template_args['key'] ); ?>
</h2>
<?php
/**
* Like get_template_part() but lets you pass args to the template file
* Args are available in the tempalte as $template_args array
* @param string filepart
* @param mixed wp_args style argument list
*/
function get_template_part_extra( $file, $template_args = array(), $cache_args = array() ) {
$template_args = wp_parse_args( $template_args );
$cache_args = wp_parse_args( $cache_args );
if ( $cache_args ) {
foreach ( $template_args as $key => $value ) {
if ( is_scalar( $value ) || is_array( $value ) ) {
$cache_args[$key] = $value;
} else if ( is_object( $value ) && method_exists( $value, 'get_id' ) ) {
$cache_args[$key] = call_user_method( 'get_id', $value );
}
}
if ( ( $cache = wp_cache_get( $file, serialize( $cache_args ) ) ) !== false ) {
if ( ! empty( $template_args['return'] ) )
return $cache;
echo $cache;
return;
}
}
$file_handle = $file;
do_action( 'start_operation', 'hm_template_part::' . $file_handle );
if ( file_exists( get_stylesheet_directory() . '/' . $file . '.php' ) )
$file = get_stylesheet_directory() . '/' . $file . '.php';
elseif ( file_exists( get_template_directory() . '/' . $file . '.php' ) )
$file = get_template_directory() . '/' . $file . '.php';
ob_start();
$return = require( $file );
$data = ob_get_clean();
do_action( 'end_operation', 'hm_template_part::' . $file_handle );
if ( $cache_args ) {
wp_cache_set( $file, $data, serialize( $cache_args ), 3600 );
}
if ( ! empty( $template_args['return'] ) )
if ( $return === false )
return false;
else
return $data;
echo $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment