So let's say I want to make new Classes for the Widgets API using some variables that the user can configure.

The only way I have figured it out is to use the eval() function. This is due to how Wordpress registers widgets. In /wp-includes/widgets.php line 515. All that gets passed to the function is the name of the Class. That function get's passed to a Factory, whose sole job is call a new instance of the Class passed to register_widget().

Is eval() the best way to dynamically create new Classes, since you can't register widgets with a Class?

Here's an example of what I'm doing.

// Variables could be data pulled from DB as well

$some_stuff = $wpdb->(...)
$my_classes = array(...);

foreach ($my_classes as $my_class) :

    class ' . $my_class . ' extends WP_Widget {
      // Extra stuff here using $my_class or $some_stuff variable

// after eval() register each widget


Got any ideas on a better way to register a potentially infinite number of Classes?

  • Why do you need infinite number of classes? You don't need new class for every possible change of variable, just interface to control those variables for the instance of the class. eval() is evil too. – Rarst Oct 23 '14 at 9:50
  • I'm effectively creating a way for clients to make their own widgets without the hassle of dealing with writing semi-ish complex php. The widgets API is easy to use, but not for someone who only knows HTML and CSS. So the variables are an array of CPT and meta information, that get's passed along to create a widget. @Rarst why is eval() evil? I cannot find any other way to do this without hacking core. Do you have a better solution? – Daron Spence Oct 23 '14 at 16:35

Your Answer

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

Browse other questions tagged or ask your own question.