Skip to content

Instantly share code, notes, and snippets.

@dana-ross
Created July 13, 2017 21:29
Show Gist options
  • Save dana-ross/e1ef409845731d25cd26e6ed8c7f4540 to your computer and use it in GitHub Desktop.
Save dana-ross/e1ef409845731d25cd26e6ed8c7f4540 to your computer and use it in GitHub Desktop.
Global-less WordPress Templating
<?php
/**
* WordPress template renderer that avoids using global variables
* @param string Name of a template to load
* @param array $args Template variables
* @return string|WP_Error rendered template or an error
* NOTE: Untested
*/
function render_template( $template_name, array $args ) {
$file = locate_template( [$template_name], false);
if( '' === $file || !file_exists( $file ) ) {
return new WP_Error( 'not found', __( 'The requested template file could not be found', 'textdomain' ), $template_name );
}
ob_start();
include $filename;
return ob_get_clean();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment