1

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);
}

1 Answer 1

1

Solved issue of dynamic function name by using $shortcode var as function name

foreach ($shortcodes as $shortcode) {

  add_shortcode($shortcode, function ($atts) use ($shortcode) {

    $filepath = str_replace('_', '-', $shortcode);

    ob_start(); 
    require_once(get_stylesheet_directory() . '/template-parts/' . $filepath . '.php');
    return ob_get_clean();
  });
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.