register child class in another plugin

I question the wisdom of extending a class from another plugin. You have no idea what will happen next time that other plugin gets updated.

However, generally speaking you can control when in a hook “queue” a function runs by passing a third parameter– a priority. So pass a priority high enough and your function should run after the other plugin’s function.

add_action(
  'widgets_init', 
  create_function('', 'register_widget("Bar");')
  ,100
);

I don’t know if that will work in your case. I’ve never tried it.

You should also be aware that you could have trouble because of plugin load order.

Changing Plugin Load Order
Does an activated plugin automatically mean its methods are available to other WP functions?

widget_init runs after plugins_loaded so that probably won’t be an issue in you case.

On further investigation… I get errors involving missing variables required by the constructor. The following works.

if ( ! class_exists( 'Foo' ) ) {
  class Foo extends WP_Widget {
      /*constructs etc*/
      function __construct($id = 'twidg', $descr="Test Widget", $opts = array()) {
    $widget_opts = array();
    parent::__construct($id,$descr,$widget_opts);
      /*do stuff*/
      }
  }
}
function rw_cb() {
register_widget("Foo");
}
add_action('widgets_init', 'rw_cb');

class Bar extends Foo {     
    function __construct() {
      $widget_opts = array();
      parent::__construct('twidgextended','Test Widget 2',$widget_opts);
    }
}
function rw_cb_2() {
  register_widget("Bar");
}
add_action('widgets_init', 'rw_cb_2');

When each component is pasted into a dummy plugin file, it works. The only time I get a fatal error involving a class file not found is if I try to activate the plugin with the Bar class definition, before the plugin with the Foo definition, which makes sense.

Wrapping that block as follows solves that issue though and you can activate in any order.

if (class_exists('Foo')) {
  class Bar extends Foo {     
      function __construct() {
    $widget_opts = array();
    parent::__construct('twidgextended','Test Widget 2',$widget_opts);
      }
  }

  function rw_cb_2() {
    register_widget("Bar");
  }
  add_action('widgets_init', 'rw_cb_2');
}

Leave a Comment