units()) { return; } add_filter('dynamic_sidebar_params', [$this, 'inject']); } public function inject($params) { if (empty($params[0]['id']) || is_admin() || !AdGhost_Helper::ads_live()) { return $params; } $sidebar = (string) $params[0]['id']; $position = $this->seen[$sidebar] = ($this->seen[$sidebar] ?? 0) + 1; $total = 0; $all = get_option('sidebars_widgets', []); if (is_array($all)) { $total = isset($all[$sidebar]) ? count((array) $all[$sidebar]) : 0; } foreach ($this->units() as $i => $unit) { if (isset($this->placed[$i])) { continue; } $pinned = trim((string) ($unit['sidebarId'] ?? '')); if ($pinned !== '') { if ($pinned !== $sidebar) { continue; } } else { if ($this->target === null) { $this->target = self::primary_sidebar() ?? $sidebar; } if ($this->target !== $sidebar) { continue; } } $after = max(1, absint($unit['insertionValue'] ?? 1)); if ($total > 0) { $after = min($after, $total); } if ($position !== $after) { continue; } $this->placed[$i] = true; if (class_exists('AdGhost_Targeting') && (AdGhost_Targeting::page_exclusion_reason() !== null || AdGhost_Targeting::unit_exclusion_reason($unit) !== null)) { continue; } if (class_exists('AdGhost_IVT_Manager') && !AdGhost_IVT_Manager::ads_allowed()) { continue; } $index = AdGhost_Placement_State::get_zone_count('sidebar'); if (!$this->budget_left()) { continue; } AdGhost_Placement_State::mark_block_inserted('sidebar_' . $index, 'sidebar', [ 'unit_name' => $unit['name'] ?? 'sidebar', ]); $params[0]['after_widget'] = ($params[0]['after_widget'] ?? '') . AdGhost_Ad_Container::render($unit, 'sidebar', $index); } return $params; } public static function primary_sidebar() { global $wp_registered_sidebars; if (empty($wp_registered_sidebars) || !is_array($wp_registered_sidebars)) { return null; } $active = function ($id) { return function_exists('is_active_sidebar') ? is_active_sidebar($id) : true; }; foreach (['sidebar-1', 'sidebar', 'primary', 'primary-sidebar', 'main-sidebar', 'sidebar-primary', 'right-sidebar', 'blog-sidebar'] as $id) { if (isset($wp_registered_sidebars[$id]) && $active($id)) { return $id; } } foreach ($wp_registered_sidebars as $id => $area) { $label = strtolower($id . ' ' . ($area['name'] ?? '')); if (preg_match('/sidebar|primary/', $label) && !preg_match('/footer|header|bottom|top|content|below|above|shop|off-?canvas/', $label) && $active($id)) { return (string) $id; } } return null; } private function budget_left() { $max = absint(get_option('adghost_max_ads_per_page', 5)); if ($max <= 0) { return true; } $placed = 0; foreach (AdGhost_Placement_Engine::CAPPED_ZONES as $zone) { $placed += AdGhost_Placement_State::get_zone_count($zone); } return $placed < $max; } private function units() { static $units = null; if ($units === null) { $units = array_values(array_filter(AdGhost_Helper::units(), function ($unit) { return ($unit['placementMode'] ?? 'auto') !== 'manual' && AdGhost_Helper::get_unit_position($unit) === 'sidebar'; })); } return $units; } }