context[CONTEXT_KEY]); $args = filter_query_vars(build_query_vars_from_query_block($core_block, 1), $block, 1, true); $offset = max(0, (int) ($args['offset'] ?? 0)); unset($args['paged'], $args['page']); $args = array_merge($args, [ 'fields' => 'ids', 'posts_per_page' => $offset ? PHP_INT_MAX : -1, 'nopaging' => !$offset, 'no_found_rows' => true, 'ignore_sticky_posts' => true, 'cache_results' => false, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, ]); // Preserve the author's initial offset and ordering while removing the page size. if (!$offset) $args['orderby'] = 'none'; // Let WP_Query and its hooks build SQL, but do not load every matching post ID // into PHP. Only this probe is short-circuited; the aggregate runs in MySQL. $probe = new \WP_Query(); $skip = static fn($posts, $query) => $query === $probe ? [] : $posts; add_filter('posts_pre_query', $skip, PHP_INT_MAX, 2); try { $probe->query($args); return $probe->request; } finally { remove_filter('posts_pre_query', $skip, PHP_INT_MAX); } } /** Keep aggregate results request-local and invalidate them after content/term changes. */ function initial_counts_cache_key($sql, $source) { wp_cache_add_non_persistent_groups(['fqbpro_choice_counts']); return \Fqbpro\Plugin\Compatibility\Languages\cache_key($source . '|' . $sql); } /** One aggregate per taxonomy/child-term mode; count each matching post only once per branch. */ function initial_term_counts($sql, $taxonomy, $include_children) { global $wpdb; $key = initial_counts_cache_key($sql, $taxonomy . '|' . (int) $include_children); $cached = wp_cache_get($key, 'fqbpro_choice_counts'); if ($cached !== false) return $cached; $terms = get_terms(['taxonomy' => $taxonomy, 'hide_empty' => false]); if (is_wp_error($terms) || !$terms || !$sql) return []; $by_id = []; foreach ($terms as $term) $by_id[$term->term_id] = $term; $mapping = []; foreach ($terms as $term) { $ancestor = $term->term_id; $seen = []; while ($ancestor && isset($by_id[$ancestor]) && !isset($seen[$ancestor])) { $seen[$ancestor] = true; $mapping[] = $wpdb->prepare('SELECT %d AS term_id, %d AS tt_id', (int) $ancestor, (int) $term->term_taxonomy_id); $ancestor = $include_children ? $by_id[$ancestor]->parent : 0; } } // All mapping values are database IDs cast to integers; the subquery is SQL // produced by WP_Query above, not saved block text or request input. $mapping_sql = implode(' UNION ALL ', $mapping); $relationships = $wpdb->prepare('%i', $wpdb->term_relationships); // WP_Query supplies the complete initial SELECT; prepared integer SELECTs supply // the term mapping. These SQL fragments cannot be passed as value placeholders. // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Core APIs cannot aggregate per-branch counts over the saved Query SQL. $rows = $wpdb->get_results("SELECT branches.term_id, COUNT(DISTINCT rel.object_id) AS matches FROM ($mapping_sql) AS branches INNER JOIN $relationships AS rel ON rel.term_taxonomy_id = branches.tt_id INNER JOIN ($sql) AS initial_posts ON initial_posts.ID = rel.object_id GROUP BY branches.term_id", ARRAY_A); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter $counts = []; foreach ($rows as $row) $counts[$by_id[(int) $row['term_id']]->slug] = (int) $row['matches']; wp_cache_set($key, $counts, 'fqbpro_choice_counts'); return $counts; } /** Limit presentation only; existing bookmarked selections retain strict request validation. */ function scope_taxonomy_choices($configuration, $block) { if (($configuration['nativeVersion'] ?? 0) !== 1 || ($block->context[CONTEXT_KEY]['contract'] ?? '') !== 'v4') return $configuration; $sql = null; foreach ($configuration['nativeControls'] as &$control) { if ($control['kind'] !== 'choice' || (!str_starts_with($control['sourceId'], 'taxonomy:') && !in_array($control['sourceId'], ['post:author', 'post:post_type'], true)) || !empty($control['errors'])) continue; if ($sql === null) $sql = initial_query_sql($block); $counts = str_starts_with($control['sourceId'], 'post:') ? initial_post_field_counts($sql, $control['sourceId'] === 'post:author' ? 'post_author' : 'post_type') : initial_term_counts($sql, substr($control['sourceId'], 9), $control['settings']['includeChildren']); foreach ($control['choices'] as &$choice) $choice['count'] = $counts[$choice['value']] ?? 0; unset($choice); $control['visibleChoices'] = array_values(array_filter($control['choices'], static fn($choice) => !empty($control['settings']['showEmpty']) || $choice['count'] > 0)); } unset($control); return $configuration; } /** Count built-in choices across the saved initial query, including all result pages. */ function initial_post_field_counts($sql, $column) { global $wpdb; if (!$sql || !in_array($column, ['post_author', 'post_type'], true)) return []; $key = initial_counts_cache_key($sql, $column); $cached = wp_cache_get($key, 'fqbpro_choice_counts'); if ($cached !== false) return $cached; $column_sql = $wpdb->prepare('%i', $column); $posts = $wpdb->prepare('%i', $wpdb->posts); // Only the allowlisted, prepared column/table and WP_Query's initial SELECT // enter this aggregate. Do not escape or re-prepare the complete core SQL. // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Core APIs cannot aggregate field counts over the saved Query SQL. $rows = $wpdb->get_results("SELECT p.$column_sql AS choice, COUNT(DISTINCT p.ID) AS matches FROM $posts AS p INNER JOIN ($sql) AS initial_posts ON initial_posts.ID = p.ID GROUP BY p.$column_sql", ARRAY_A); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter $counts = []; foreach ($rows as $row) $counts[(string) $row['choice']] = (int) $row['matches']; wp_cache_set($key, $counts, 'fqbpro_choice_counts'); return $counts; }