If you’re working with WordPress, here’s a neat snippet I’ve picked up recently. It allows you to call a template file anywhere in the content body using a shortcode.
You might have a panel with specific functionality or a loop within it, so to be able to drop it in anywhere is pretty handy!
<? // include template using WP shortcode function my_shortcode_include() { ob_start(); // include your template e.g. /inc/random-panel.php get_template_part('inc/random-panel'); $output_string = ob_get_contents(); ob_end_clean(); return $output_string; } add_shortcode('panel', 'my_shortcode_include'); ?>
Here we are including the template random-panel.php
using the shortcode [panel]
.
I tend to keep all my includes / template chunks in a folder called /inc
in my WordPress theme. The file location therefore is /inc/random-panel.php
.
The lines prefixes with ob_
sanitise the content so you shouldn’t get any rogue <p>
or <br />
elements.