0

I built a bunch of basic Mustache templates for a project, and now I'm wanting to effectively make them available to WordPress as widgets.

//This uses Composer to manage dependencies (Mustache).
require 'vendor/autoload.php';

$mustaches = array_diff(scandir(dirname(__FILE__) . '/templates'), array('..', '.'));
$templates = array();
foreach ($mustaches as $mustache) {
  $code = file_get_contents(dirname(__FILE__) . '/templates/' . $mustache);
  $templates[$mustache] = array(
    'id' => str_replace('.mustache', '', $mustache),
    'template' => $code,
    'name' => preg_replace('/\{\{\! name\: \"(.*?)\"\}\}/', '$1' , explode("\n", $code, 1)), //Human name defined in comment at start of template.
  );
}

Now what do I do? I can't dynamically define classes like so:

foreach ($mustaches as $mustache) {    
  class $mustache extends WP_Widget { ... 

This gives a syntax error because dynamic extension isn't really a thing anyone does.

How do I register multiple widgets with a single class definition?

Thank you!

  • I haven't gotten any more responses a week later, so accepting Rarst's. Feel free to add more answers, I'll at least upvote them. – aendrew Jul 12 '13 at 11:08
  • *upvote them if helpful, rather. – aendrew Jul 12 '13 at 11:19
1

How do I register multiple widgets with a single class definition?

You don't. Modern class based Widget API in WP assumes that one class corresponds to one widget. Note that you can still have intermediary subclasses - (extend WP_Widget, then extend it once more) but what you register in the end is still one widget per class.

From your question it's not very clear what your mustache templates are functionally and how varied they are.

If they are similar enough what you could do is create single widget and expose template list in interface to choose for each widget instance.

  • Fair enough. The templates are a bit varied functionally — two allow the user to select an image, which is then styled a specific way; another is a bunch of styled text. I thought about loading the admin form with fields and showing/hiding certain ones based on the value of a select field, but that seems rather unwieldy. Thanks for getting back to me! – aendrew Jul 6 '13 at 0:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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