Skip to content

Instantly share code, notes, and snippets.

@OzzyCzech
Last active Dec 11, 2015
Embed
What would you like to do?
Registration of the Widgets in Wordpress can be confusing there is simple way how to handle it.
<?php
$widgets = new Widgets();
$widgets->unregisterAllWidgets(); // delete all placed Widgets
$widgets->add(
'text',
array(
'title' => 'About us',
'text' => 'Simple text about us',
'filter' => true,
'classes' => '',
'ids' => null,
),
'footer-1'
);
// ...
<?php
class Widgets {
private $widgets = array();
private $options = array();
public function __construct() {
$this->options = wp_get_sidebars_widgets();
}
public function unregisterAllWidgets() {
foreach ($this->options as $name => $values)
$this->options[$name] = array();
}
public function cleanWidgetSettings($type, $multi = null) {
$this->widgets[$type] = array();
if ($multi !== null) $this->widgets[$type]['_multiwidget'] = (int)(bool)$multi;
}
public function setMultiWidget($type, $val = 1) {
$this->widgets[$type]['_multiwidget'] = $val;
}
public function add($type, array $options, $area = null) {
$this->widgets[$type][] = $options;
if ($area !== null) {
if (array_key_exists($area, $this->options) === false) {
throw new Exception('Widget area ' . $area . ' not exists.');
}
end($this->widgets[$type]);
$this->options[$area][] = $type . '-' . key($this->widgets[$type]);
}
}
public function __destruct() {
foreach ($this->widgets as $name => $settings) {
if (!array_key_exists('_multiwidget', $settings)) $settings['_multiwidget'] = 1;
update_option('widget_' . $name, $settings);
}
wp_set_sidebars_widgets($this->options);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment