Select Page

There’s an easy way you can load theme template files in your content. You can display theme template contents using a shortcode. You might have template files in your theme that you want to load inside your content.

This shortcode will allow you to load any HTML or PHP file inside your theme’s directory. The contents of this file will be displayed inside your content wherever you place this shortcode.

Add this code to your theme’s functions.php file:

function load_template_file_shortcode($atts){

	// If there is no file attribute, then this will be false...
	$atts = shortcode_atts(array('file' => false), $atts);
	
	// The attribute file for this shortcode contains the name of the file.
	if( $atts['file'] && file_exists($atts['file']) ){
		return require($atts['file']); // Require the PHP file.
	}
	return ""; // Return nothing if file isn't available.
}

// Add the shortcode.
add_shortcode('load_template_file', 'load_template_file_shortcode');

If you use the load_template_file shortcode, whatever PHP file name you pass to it as the file attribute will be loaded.

You should be very careful with this shortcode and only use it if you really need it. A better way to use this shortcode would be to have a list of allowed files.

function load_template_file_shortcode($atts){

	// For security, only allow the files you know are safe to load inside content.
	$allowed_files = ['test.php', 'my-custom.php', 'safe.php'];

	// If there is no file attribute, then this will be false...
	$atts = shortcode_atts(array('file' => FALSE), $atts);
	
	// The attribute file for this shortcode contains the name of the file.
	if( in_array($atts['file'], $allowed_files) && $atts['file'] && file_exists($atts['file']) ){
		return require($atts['file']); // Require the PHP file.
	}
	return ""; // Return nothing if file isn't available.
}

add_shortcode('load_template_file', 'load_template_file_shortcode');