I have a custom theme that includes several template parts. I intend to use theme template parts within theme files as well as using them as shortcodes.
To create the shortcodes I am currently wrapping each template part in its own shortcode function. Example:
function foo_shortcode() {
ob_start();
require_once( get_stylesheet_directory() . '/template-parts/foo.php');
return ob_get_clean();
} add_shortcode('foo', 'foo_shortcode');
Is it possible to output the shortcode functions using a foreach
loop based on an array of short code names? All template parts are stored in the same folder.
My current code gives error Parse error: syntax error, unexpected '$function_name' (T_VARIABLE), expecting '('
Current code:
$shortcodes = array(
'foo',
'bar',
'lorem',
'ipsum',
'dolah'
);
foreach ($shortcodes as $shortcode) {
$filepath = get_stylesheet_directory() . '/template-parts/' . $shortcode . '.php';
$function_name = $shortcode . "_function";
function $function_name () {
ob_start();
require_once($filepath);
return ob_get_clean();
} add_shortcode($shortcode, $function_name);
}