60) { return []; } $ids = []; foreach ($elements as $el) { if (!is_array($el)) { continue; } if (($el['type'] ?? '') === 'component') { $id = (int) ($el['settings']['component_id'] ?? 0); if ($id > 0) { $ids[$id] = true; } } if (!empty($el['children']) && is_array($el['children'])) { foreach (self::component_ids($el['children'], $depth + 1) as $child) { $ids[$child] = true; } } } return array_map('intval', array_keys($ids)); } /** Rewrites the index rows of a post from its (sanitized) elements. */ public static function index(int $post_id, array $elements): void { if ($post_id <= 0) { return; } delete_post_meta($post_id, self::META); foreach (self::component_ids($elements) as $id) { if ($id !== $post_id) { add_post_meta($post_id, self::META, (string) $id); } } } /** @return int[] posts (not trashed, not revisions) that place the component */ public static function posts(int $component_id): array { if ($component_id <= 0) { return []; } $types = function_exists('get_post_types') ? array_values(array_diff((array) get_post_types(), ['revision', 'attachment', 'nav_menu_item', 'customize_changeset', 'oembed_cache', 'user_request', 'wp_block', 'wp_template', 'wp_template_part', 'wp_global_styles', 'wp_navigation', 'wp_font_family', 'wp_font_face'])) : ['post', 'page']; $ids = get_posts([ 'post_type' => $types ?: ['post', 'page'], 'post_status' => ['publish', 'draft', 'pending', 'private', 'future'], 'numberposts' => -1, 'fields' => 'ids', // phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- finds the pages that use a component by its usage meta; bounded, cached lookup. 'meta_key' => self::META, 'meta_value' => (string) $component_id, // phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value 'no_found_rows' => true, ]); return array_values(array_unique(array_map('intval', is_array($ids) ? $ids : []))); } public static function count(int $component_id): int { return count(self::posts($component_id)); } }