$s) { $areas[] = [ 'id' => $id, 'name' => $s['name'], 'description' => $s['description'], ]; } return ['widget_areas'=>$areas,'count'=>count($areas)]; } public static function getWidgetArea(array $args): array { $sidebar_id = $args['sidebar_id']; $sidebars = wp_get_sidebars_widgets(); if (!isset($sidebars[$sidebar_id])) { throw new \RuntimeException("Widget area not found: $sidebar_id"); } global $wp_registered_widgets; $widgets = []; foreach ((array)$sidebars[$sidebar_id] as $widget_id) { $parts = explode('-', $widget_id); $number = array_pop($parts); $base_id = implode('-', $parts); $settings = get_option("widget_{$base_id}"); $widgets[] = [ 'widget_id' => $widget_id, 'base_id' => $base_id, 'number' => is_numeric($number) ? (int)$number : $number, 'name' => $wp_registered_widgets[$widget_id]['name'] ?? $widget_id, 'settings' => (is_array($settings) && isset($settings[(int)$number])) ? $settings[(int)$number] : null, ]; } return ['sidebar_id'=>$sidebar_id,'widgets'=>$widgets,'count'=>count($widgets)]; } public static function listRegisteredWidgets(array $args): array { global $wp_registered_widget_controls; $widgets = []; $seen = []; foreach ((array)$wp_registered_widget_controls as $id => $w) { $base = $w['id_base'] ?? $id; if (in_array($base, $seen, true)) continue; $seen[] = $base; $widgets[] = ['id_base'=>$base,'name'=>$w['name'],'classname'=>$w['classname']??'']; } usort($widgets, fn($a,$b)=>strcmp($a['name'],$b['name'])); return ['widgets'=>$widgets,'count'=>count($widgets)]; } public static function updateWidgetArea(array $args): array { $sidebar_id = $args['sidebar_id']; $widget_ids = $args['widget_ids']; // ordered array of widget IDs if (!is_array($widget_ids)) throw new \RuntimeException("widget_ids must be an array."); $sidebars = wp_get_sidebars_widgets(); $sidebars[$sidebar_id] = array_map('sanitize_text_field', $widget_ids); wp_set_sidebars_widgets($sidebars); return ['sidebar_id'=>$sidebar_id,'updated'=>true,'widget_count'=>count($widget_ids)]; } public static function removeWidgetFromArea(array $args): array { $sidebar_id = $args['sidebar_id']; $widget_id = $args['widget_id']; $sidebars = wp_get_sidebars_widgets(); if (!isset($sidebars[$sidebar_id])) throw new \RuntimeException("Widget area not found: $sidebar_id"); $sidebars[$sidebar_id] = array_values(array_filter($sidebars[$sidebar_id], fn($w) => $w !== $widget_id)); wp_set_sidebars_widgets($sidebars); return ['sidebar_id'=>$sidebar_id,'widget_id'=>$widget_id,'removed'=>true]; } }