Adding widgets programatically: how to avoid collisions?

Looking at the source code that WordPress uses to register widgets here, there’s a $number parameter defined, in line 242, as:

The unique order number of this widget instance compared to other instances of the same class.

The function _set($number) stores this ID number attached to the base identifier string of the widget.

Then, the function get_settings retrieves all configuration options for all the instances of the widget, in all sidebars. And when they are registered is when this $number part of the full widget ID is generated:

 public function _register() {
                $settings = $this->get_settings();
                $empty = true;

                if ( is_array($settings) ) {
                        foreach ( array_keys($settings) as $number ) {
                                if ( is_numeric($number) ) {
                                        $this->_set($number);
                                        $this->_register_one($number);
                                        $empty = false;
                                }
                        }
                }
[...]

In the register_one function, we find this:

integer $number Optional. The unique order number of this widget instance
compared to other instances of the same class.

So, the combination of the ID $number with the $id_base name has to be unique for all the instances of your widget, in any sidebar.

Leave a Comment