10, 'h1' => 9, 'first_100_words' => 7, 'subheadings' => 6, 'meta_description' => 6, 'slug' => 3, 'image_alt' => 5, 'links' => 8, 'content_length' => 6, ); const DENSITY_WEIGHT = 20; const READABILITY_WEIGHT = 20; /** * 3.3 (multi-keyword, zvedene-tz): the maximum number of SECONDARY * keywords a post may store — on top of, not counting, the one primary * keyword in `_abds_seo_focus_keyword` — matching "up to 5 keywords * total, the first starred as primary" from the backlog (5 - 1 = 4). */ const MAX_SECONDARY_KEYWORDS = 4; /** * The CHECK_WEIGHTS keys that depend on the keyword being tested — 7 of * the 9 checks; `links` and `content_length` don't test for a keyword at * all, so they're excluded here (see keyword_dependent_points()). */ const KEYWORD_DEPENDENT_CHECKS = array( 'title', 'h1', 'first_100_words', 'subheadings', 'slug', 'meta_description', 'image_alt' ); /** * Sum of KEYWORD_DEPENDENT_CHECKS' CHECK_WEIGHTS (46) plus DENSITY_WEIGHT * (20, also keyword-dependent) — the REFERENCE/default max a per-keyword * chip score normalizes against, when every keyword-dependent check is * applicable. Verified against CHECK_WEIGHTS: 10+9+7+6+3+6+5 = 46, +20 = 66. * * NOT the actual denominator every call uses — keyword_dependent_points() * returns its own `max`, which drops below this when image_alt is * inapplicable (zero images in the content — see * applicable_check_weights()); this constant documents what that * `max` equals in the common case and is not read anywhere else. * * Deliberately NOT the full 100 even in that common case: giving every * secondary keyword a free ride on the 34 keyword-independent points * (links/content_length/readability) would flatten every chip's color * toward the same value — the color exists to tell keywords apart, so * it has to come only from what actually differs between them. */ const KEYWORD_DEPENDENT_MAX_POINTS = 66; /** * Keyword frequency/placement helper. * * @var ABDS_SEO_Keyword_Extractor */ protected ABDS_SEO_Keyword_Extractor $keywords; /** * Readability scoring helper. * * @var ABDS_SEO_Readability_Checker */ protected ABDS_SEO_Readability_Checker $readability; /** * Per-block recommendation engine (heading/paragraph/image/list). * * @var ABDS_SEO_Block_Recommendations */ protected ABDS_SEO_Block_Recommendations $block_recommendations; /** * Constructor. */ public function __construct() { $this->keywords = new ABDS_SEO_Keyword_Extractor(); $this->readability = new ABDS_SEO_Readability_Checker(); $this->block_recommendations = new ABDS_SEO_Block_Recommendations( $this->keywords ); } /** * Analyzes a post's content against a focus keyword and persists the * resulting content score to wp_abds_seo_page_scores. * * @param int $post_id Post ID to analyze. * @param string $focus_keyword Focus keyword (or phrase). * @return array{post_id:int, focus_keyword:string, content_score:?int, content_score_points:?int, content_score_max:?int, keyword_density:float, checks:array, readability:array, recommendations:array, block_recommendations:array, content_boundary:string} */ public function analyze( int $post_id, string $focus_keyword ): array { $post = get_post( $post_id ); if ( ! $post ) { return $this->empty_result( $post_id, $focus_keyword ); } $focus_keyword = trim( $focus_keyword ); if ( '' === $focus_keyword ) { return $this->empty_result( $post_id, $focus_keyword ); } $title = get_post_meta( $post_id, '_abds_seo_title', true ); $title = '' !== $title ? $title : get_the_title( $post_id ); $result = $this->compute( $post_id, $focus_keyword, array( 'title' => (string) $title, 'post_title' => (string) $post->post_title, 'description' => (string) get_post_meta( $post_id, '_abds_seo_description', true ), 'slug' => (string) $post->post_name, 'content' => (string) $post->post_content, ) ); $this->persist_result( $post_id, $result['content_score'], $result['recommendations'] ); return $result; } /** * Same analysis `analyze()` runs, but against draft/in-progress field * values instead of the saved post row, and — deliberately — never * persists to `wp_abds_seo_page_scores`. For live, debounced * recalculation while the user is still typing (Gutenberg sidebar, * Classic Editor meta box): nothing about "what you're about to save" * should overwrite the real score for what's actually published. * * Every `$overrides` key is optional; anything not passed falls back to * the post's current saved value (or, for `content`, requires either an * override or a real post — an unsaved-content-only preview for a new, * never-saved post has no baseline to fall back to and returns the * empty result, same as `analyze()` does for a missing post). * * @param int $post_id Post ID (source of any field not overridden). * @param string $focus_keyword Focus keyword (or phrase) — always the live/draft value, no post-meta fallback. * @param array{title?:string, post_title?:string, description?:string, slug?:string, content?:string} $overrides Draft field values. * @return array{post_id:int, focus_keyword:string, content_score:?int, content_score_points:?int, content_score_max:?int, keyword_density:float, checks:array, readability:array, recommendations:array, block_recommendations:array, content_boundary:string} */ public function preview( int $post_id, string $focus_keyword, array $overrides = array() ): array { $focus_keyword = trim( $focus_keyword ); if ( '' === $focus_keyword ) { return $this->empty_result( $post_id, $focus_keyword ); } return $this->compute( $post_id, $focus_keyword, $this->resolve_field_data( $post_id, $overrides ) ); } /** * Resolves the field values `preview()` and `score_keywords()` (3.3) * both score against: each `$overrides` key wins when present, else the * post's current saved value, else '' when there's no real post either. * Pulled out of `preview()` so `score_keywords()` doesn't duplicate this * resolution — both need "draft fields over saved fields", neither * should have its own slightly-different copy of the fallback order. * * @param int $post_id Post ID (source of any field not overridden). * @param array{title?:string, post_title?:string, description?:string, slug?:string, content?:string} $overrides Draft field values. * @return array{title:string, post_title:string, description:string, slug:string, content:string} */ protected function resolve_field_data( int $post_id, array $overrides = array() ): array { $post = get_post( $post_id ); $title = $overrides['title'] ?? ( $post ? get_post_meta( $post_id, '_abds_seo_title', true ) : '' ); $title = '' !== $title ? $title : ( $post ? get_the_title( $post_id ) : '' ); return array( 'title' => (string) $title, 'post_title' => (string) ( $overrides['post_title'] ?? ( $post ? $post->post_title : '' ) ), 'description' => (string) ( $overrides['description'] ?? ( $post ? get_post_meta( $post_id, '_abds_seo_description', true ) : '' ) ), 'slug' => (string) ( $overrides['slug'] ?? ( $post ? $post->post_name : '' ) ), 'content' => (string) ( $overrides['content'] ?? ( $post ? $post->post_content : '' ) ), ); } /** * 3.3 (multi-keyword): scores each of several keywords against the SAME * resolved field data — the fields (and the post) are fetched exactly * once here, then keyword_dependent_points() runs once per keyword, * rather than each chip re-running a full analyze()/preview() (which * would also re-run block_recommendations and readability, neither of * which depends on which keyword is being scored). * * @param int $post_id Post ID (source of any field not overridden). * @param string[] $keywords Keywords to score; blank entries after trim() are skipped. * @param array{title?:string, post_title?:string, description?:string, slug?:string, content?:string} $overrides Draft field values, same shape preview() takes. * @return array Map of keyword => 0-100 score, normalized against that * call's own applicable-points max — see keyword_dependent_points(). */ public function score_keywords( int $post_id, array $keywords, array $overrides = array() ): array { $data = $this->resolve_field_data( $post_id, $overrides ); $scores = array(); foreach ( $keywords as $keyword ) { $keyword = trim( (string) $keyword ); if ( '' === $keyword ) { continue; } $result = $this->keyword_dependent_points( $data, $keyword ); $scores[ $keyword ] = $result['max'] > 0 ? (int) round( ( $result['points'] / $result['max'] ) * 100 ) : 0; } return $scores; } /** * The keyword-dependent subset of compute()'s checks — 7 of the 9 * CHECK_WEIGHTS checks plus density — as raw points and their own max, * for one keyword against already-resolved field data. Not merged into * compute() itself: compute() also needs the 2 keyword-INdependent * checks (links, content_length) plus readability and * block_recommendations, none of which score_keywords() needs to * repeat per keyword. * * `max` is no longer always KEYWORD_DEPENDENT_MAX_POINTS (66) — "can't * see its subject" (see applicable_check_weights()) now genuinely * excludes image_alt's weight from both points and max when the * content has zero images, the same true-exclusion treatment * compute()/calculate_score() use, rather than the earlier full-credit * reading. KEYWORD_DEPENDENT_MAX_POINTS stays as the reference/default * value for the common case (images present). * * @param array{title:string, post_title:string, description:string, slug:string, content:string} $data Resolved field values (see resolve_field_data()). * @param string $keyword Keyword (or phrase) to test. * @return array{points:int, max:int} */ protected function keyword_dependent_points( array $data, string $keyword ): array { $title = $data['title']; $post_title = $data['post_title'] ?? $title; $description = $data['description']; $slug = $data['slug']; // P3 component 3 (2026-09-05): this path is deliberately still // direct-from-content, no boundary-fetch fallback — see // resolve_content_units()'s own docblock note on why the live- // typing/chip-score path never needs one (the block editor's own // model always yields real, visible block markup when it's the // active editor). But per point 1 of that migration, no check // still accepts a raw string either way, so the same // (fallback-free) adapter call builds units here too. $units = ABDS_SEO_Rendered_HTML_Content_Adapter::units_from_html( $data['content'] ); $units_text = self::units_text( $units ); $units_html = self::units_html( $units ); $first_100 = $this->keywords->first_words( $units_text, 100 ); $applicable_weights = array_intersect_key( $this->applicable_check_weights( $this->content_has_images( $units_html ), true ), array_flip( self::KEYWORD_DEPENDENT_CHECKS ) ); $checks = array( 'title' => $this->keywords->contains( $title, $keyword ), 'h1' => $this->check_h1( $post_title, $units, $keyword ), 'first_100_words' => $this->keywords->contains( $first_100, $keyword ), 'subheadings' => $this->check_heading_group( $units, $keyword, array( 2, 3, 4, 5, 6 ) ), 'slug' => $this->check_slug( $slug, $keyword ), 'meta_description' => $this->keywords->contains( $description, $keyword ), 'image_alt' => $this->check_image_alt( $units, $keyword ), ); $points = 0; foreach ( $checks as $key => $passed ) { if ( $passed && isset( $applicable_weights[ $key ] ) ) { $points += $applicable_weights[ $key ]; } } $max = array_sum( $applicable_weights ); $density = $this->keywords->density( $units_text, $keyword ); $points += ( $density >= self::DENSITY_MIN && $density <= self::DENSITY_MAX ) ? self::DENSITY_WEIGHT : (int) ( self::DENSITY_WEIGHT / 2 ); $max += self::DENSITY_WEIGHT; return array( 'points' => $points, 'max' => $max, ); } /** * The actual scoring logic, shared by `analyze()` (saved post, persists) * and `preview()` (draft fields, never persists). Pulled out so both * entry points run the exact same checks — no separate "preview logic" * to drift out of sync with the real one. * * @param int $post_id Post ID (only used to label the result and for block-recommendation client-id lookups). * @param string $focus_keyword Focus keyword (already trimmed/validated non-empty by the caller). * @param array{title:string, post_title:string, description:string, slug:string, content:string} $data Field values to score. * @return array{post_id:int, focus_keyword:string, content_score:?int, content_score_points:?int, content_score_max:?int, keyword_density:float, checks:array, readability:array, recommendations:array, block_recommendations:array, content_boundary:string} */ protected function compute( int $post_id, string $focus_keyword, array $data ): array { $title = $data['title']; $post_title = $data['post_title'] ?? $title; $description = $data['description']; $slug = $data['slug']; $content = $data['content']; // P3 component 3 (2026-09-05): every content-dependent check below // reads from ONE ContentUnit stream, never a raw string — see // resolve_content_units() for the exact trigger and 3-state result. // build_recommendations()/block_recommendations still use the // ORIGINAL $content — those exist to point at an editable Gutenberg // block, which a resolved unit stream has no equivalent of. $resolved = $this->resolve_content_units( $post_id, $content ); $units = $resolved['units']; // "A check that can't see its subject doesn't score" (2026-09-04 // coordinator decision) taken to its actual conclusion: when the // fallback ran and STILL found nothing (NOT_DETERMINED), there is no // content to check ANYTHING against — not just image_alt/links. // Returning a computed number here (even a "fair" one) would be a // confident-looking score for a page this plugin never actually // read, exactly the failure mode 1.4's sitemap CHECK_FAILED state // exists to avoid. No content_score at all, same discipline. if ( ABDS_SEO_Content_Boundary_Detector::METHOD_NOT_DETERMINED === $resolved['boundary_method'] ) { return $this->unavailable_result( $post_id, $focus_keyword ); } $units_text = self::units_text( $units ); $units_html = self::units_html( $units ); $first_100 = $this->keywords->first_words( $units_text, 100 ); $checks = array( 'title' => $this->keywords->contains( $title, $focus_keyword ), 'h1' => $this->check_h1( $post_title, $units, $focus_keyword ), 'first_100_words' => $this->keywords->contains( $first_100, $focus_keyword ), 'subheadings' => $this->check_heading_group( $units, $focus_keyword, array( 2, 3, 4, 5, 6 ) ), 'slug' => $this->check_slug( $slug, $focus_keyword ), 'meta_description' => $this->keywords->contains( $description, $focus_keyword ), 'image_alt' => $this->check_image_alt( $units, $focus_keyword ), 'links' => $this->check_links( $units ), 'content_length' => $this->keywords->word_count( $units_text ) >= self::MIN_CONTENT_WORDS, ); // "Can't see its subject" (universal, 2026-09-04): image_alt/links // are excluded from the score's denominator itself — not credited // in full — whenever the analyzed content has zero of the element // the check is about. Computed ONCE here and passed into BOTH // calculate_score() and build_score_breakdown() so the two can // never independently drift on what "applicable" means for this // post (see calculate_score()'s own docblock for the earlier, // rejected full-credit design and why this replaced it). $applicable_weights = $this->applicable_check_weights( $this->content_has_images( $units_html ), $this->content_has_links( $units_html ) ); $density = $this->keywords->density( $units_text, $focus_keyword ); // Readability now scores the SAME resolved unit stream the checks // above use, not the raw, unresolved $content — a fallback that // found real rendered text must have that text's readability // counted; a fallback that found nothing already returned above. // Recommendations/block_recommendations deliberately keep using // the RAW $content — they exist to point at an editable Gutenberg // block, which the resolved stream has no equivalent of. $readability = $this->readability->analyze( $units_html ); $recommendations = $this->build_recommendations( $checks, $density, $content ); $score = $this->calculate_score( $checks, $density, $readability['score'], $applicable_weights ); $score_breakdown = $this->build_score_breakdown( $checks, $density, $readability['score'], $applicable_weights ); $block_recommendations = array_map( array( $this, 'translate_block_recommendation' ), $this->block_recommendations->analyze( parse_blocks( $content ), $focus_keyword ) ); return array( 'post_id' => $post_id, 'focus_keyword' => $focus_keyword, // Normalized 0-100 (2026-09-05) — see calculate_score()'s own // docblock for why normalization happens here, once, rather // than every consumer needing to know `max` can vary. 'content_score' => $score['score'], // UNnormalized earned/possible — used ONLY to show "70 of 87 // points" next to the normalized score above; not itself a // second score. build_score_breakdown()'s rows sum to these // same two numbers exactly. 'content_score_points' => $score['raw_points'], 'content_score_max' => $score['max'], 'keyword_density' => $density, 'checks' => $checks, 'score_breakdown' => $score_breakdown, 'readability' => $readability, 'recommendations' => $recommendations, 'block_recommendations' => $block_recommendations, 'content_boundary' => $resolved['boundary_method'], ); } /** * The "we could not read this page's content at all" result (P3, * 2026-09-04): NOT_DETERMINED from resolve_scoring_content() means * post_content itself was empty/dynamic AND the real, rendered-page * fallback fetch either failed outright or found neither a marker, an * entry-content region, nor a post-id wrapper to trust. There is * nothing honest to score — checks/score_breakdown/readability/ * recommendations all come back empty rather than computed against an * empty string, and content_score is null, not 0 or some computed * number: a real "we checked and it's bad" 0 and "we never actually * looked" null must stay visibly different states, the same distinction * categorize_score() already makes for a post that was simply never * analyzed. persist_result() writes this null straight through — the * DB column (content_score DECIMAL(5,2)) is already nullable for * exactly this "not analyzed" case. * * @param int $post_id Post ID. * @param string $focus_keyword Focus keyword as passed in. * @return array{post_id:int, focus_keyword:string, content_score:?int, content_score_points:?int, content_score_max:?int, keyword_density:float, checks:array, readability:array, recommendations:array, block_recommendations:array, content_boundary:string} */ protected function unavailable_result( int $post_id, string $focus_keyword ): array { return array( 'post_id' => $post_id, 'focus_keyword' => $focus_keyword, 'content_score' => null, 'content_score_points' => null, 'content_score_max' => null, 'keyword_density' => 0.0, 'checks' => array(), 'score_breakdown' => array(), 'readability' => array(), 'recommendations' => array(), 'block_recommendations' => array(), 'content_boundary' => ABDS_SEO_Content_Boundary_Detector::METHOD_NOT_DETERMINED, ); } /** * The CHECK_WEIGHTS subset actually applicable to this content — full * CHECK_WEIGHTS minus image_alt when there are zero images, minus links * when there are zero links. Computed once (here) and shared by * calculate_score() and build_score_breakdown() — see calculate_score()'s * docblock for why a single shared map replaced two independent * full-credit calculations. * * Subheadings is deliberately NOT in this exclusion set, and this isn't * a gap waiting for someone to "finish the pattern" (2026-09-05 * coordinator decision, on record here so it isn't quietly reversed * later): "a check that can't see its subject doesn't score" applies * to checks whose subject is optional in the first place — a post * genuinely has no images, so there is nothing to write alt text for. * A post missing subheadings is a different case: the subject * (structure) isn't absent, the post is simply failing to have it, and * "add subheadings" is real, actionable advice the way "add alt text * to your non-existent images" is not. Subheadings therefore stays * always-applicable on the merits, independent of whether the * required/optional-input mechanism could technically be pointed at it. * * @param bool $has_images Whether the analyzed content has at least one . * @param bool $has_links Whether the analyzed content has at least one . * @return array CHECK_WEIGHTS, with 'image_alt'/'links' removed as applicable. */ protected function applicable_check_weights( bool $has_images, bool $has_links ): array { $weights = self::CHECK_WEIGHTS; if ( ! $has_images ) { unset( $weights['image_alt'] ); } if ( ! $has_links ) { unset( $weights['links'] ); } return $weights; } /** * Resolves the ContentUnit stream every content-dependent check (h1's * content-

branch, subheadings, image_alt, links, first_100_words, * content_length, density, readability) reads from — Priority 3 * component 3 (2026-09-05): no check accepts a raw content string * anymore, only this array. This is also the single entry point point 1 * of that migration's plan required — every consumer gets units, never * a string, regardless of where those units came from. * * ABDS_SEO_Rendered_HTML_Content_Adapter is now used for BOTH branches * below, including for a genuine Gutenberg post's own post_content — * not only the rendered-page fallback. ABDS_SEO_Block_Content_Adapter * cannot fill this role: parse_blocks() on Classic Editor / raw-HTML * content (no `` markers at all) yields only a * null-blockName freeform entry, which its own flatten() correctly * skips — producing an EMPTY unit array for every such post. The * rendered-HTML adapter has no such gap (block-comment markers parse * as DOMComment, invisible to its DOM walk either way), and — as of * this migration — also classifies unrecognized elements as kind * 'other' rather than dropping them, so it structurally cannot lose * content the old raw-string checks could see. * * Common case (real Gutenberg content, Classic Editor content, or any * other post_content with real visible text): units_from_html($content) * already has real text in it, used directly, boundary_method = * 'raw_content'. Only when that yields no real text at all (a page * builder storing dynamic/render_callback blocks with no static * innerHTML — confirmed live on neborak.com.ua's iDance Site Builder, * 2026-09-04 — or literally blank content) does this reach for * ABDS_SEO_Content_Boundary_Fetcher's real, frontend-rendered fetch — * and only for an existing, saved post (post_id > 0): an unsaved * draft/preview has no permalink to fetch, and preview()/score_keywords() * never reach this method with empty content anyway in practice (the * block editor's own model always yields real, visible block markup * when it's the active editor — see this method's docblock note in * compute()). * * M6 (abds-seo-pro, 2026-09-23): also called cross-plugin, from Pro's * link-suggestion service, which needs this exact same ContentUnit * stream for its own on-demand AI request rather than re-deriving it. * Widened from protected to public for that -- a pure visibility * widening, so every existing internal call site (analyze()/preview()/ * score_keywords()) keeps behaving identically. * * @param int $post_id Post ID (0/non-existent means "can't fetch"). * @param string $content Raw post_content. * @return array{units:array, boundary_method:string} * boundary_method is 'raw_content' (no fallback needed), one of * ABDS_SEO_Content_Boundary_Detector::METHOD_* (fallback used), * or METHOD_NOT_DETERMINED with an empty $units array (fallback * attempted, found nothing to score against — checks that need * it correctly fail rather than scoring against the wrong page). */ public function resolve_content_units( int $post_id, string $content ): array { $raw_units = ABDS_SEO_Rendered_HTML_Content_Adapter::units_from_html( $content ); if ( self::units_have_real_text( $raw_units ) ) { return array( 'units' => $raw_units, 'boundary_method' => 'raw_content', ); } if ( $post_id <= 0 || ! get_post( $post_id ) ) { return array( 'units' => $raw_units, 'boundary_method' => 'raw_content', ); } $fetch = ( new ABDS_SEO_Content_Boundary_Fetcher() )->fetch( $post_id ); if ( ABDS_SEO_Content_Boundary_Detector::METHOD_NOT_DETERMINED === $fetch['method'] || null === $fetch['html'] ) { return array( 'units' => array(), 'boundary_method' => ABDS_SEO_Content_Boundary_Detector::METHOD_NOT_DETERMINED, ); } return array( 'units' => ABDS_SEO_Rendered_HTML_Content_Adapter::units_from_html( $fetch['html'] ), 'boundary_method' => $fetch['method'], ); } /** * Whether any unit in the stream has real, non-empty text — the * trigger for "does this content need the rendered-page fallback at * all" in resolve_content_units(). An image unit's own text is always * '' by design (ABDS_SEO_Rendered_HTML_Content_Adapter's own docblock), * so a post whose only unit is a single image never counts as "has * real text" on its own — matching the OLD trigger exactly * (wp_strip_all_tags() on a bare `` also produces '', since alt * text is an attribute, not element text). * * @param array $units ContentUnit stream. * @return bool */ protected static function units_have_real_text( array $units ): bool { foreach ( $units as $unit ) { if ( '' !== trim( $unit['text'] ) ) { return true; } } return false; } /** * Concatenates every unit's own `text` field, in document order, with a * single space between units so adjacent units' text can't glue * together with no boundary. The one text source content_length, * first_100_words, and density all read from (P3 component 3, * 2026-09-05) — no separate re-stripping of a raw string, since each * unit's `text` is already html-stripped/whitespace-normalized by * whichever adapter produced it. * * KNOWN, ACCEPTED value change from the pre-migration behavior * (approved at acceptance review, 2026-09-05 — this was a discrepancy * surfaced by the migration's own acceptance check, not a decision made * in its original Step 0 plan, which never mentioned density at all): * the old $plain was wp_strip_all_tags() on the WHOLE raw string at once, which silently * glued two adjacent tags' text together with NO separator whenever the * source HTML itself had no whitespace between them (e.g. `

`, * common when a theme/editor doesn't insert a newline between blocks). * A unit's own text is computed from its own subtree only — the * inter-tag whitespace (or lack of it) between two SEPARATE units' * source tags was never part of either unit's own html, so it can't be * reproduced here even in principle. Confirmed live on a real Classic * Editor post (id 23, "класично" + "Бузковий" merged into one 13-char * word under the old path, correctly two words under this one) — this * changed keyword_density's displayed value on 4 of 5 real test posts, * NOT any of content_score/content_score_points/content_score_max/checks * (verified: those four matched byte-for-byte before and after). The * new value is more correct, not a regression — two genuinely separate * elements (a heading, a paragraph) should never read as one glued word * just because their source markup happened to omit whitespace between * tags — and is accepted as the new baseline going forward. * * @param array $units ContentUnit stream. * @return string */ protected static function units_text( array $units ): string { return trim( implode( ' ', array_column( $units, 'text' ) ) ); } /** * Concatenates every unit's own `html` field, in document order. The * one HTML source readability and the links check both read from (P3 * component 3, 2026-09-05) — readability needs real `

...

` * boundaries for its own paragraph-length detection (see * ABDS_SEO_Readability_Checker::split_paragraphs()), which each unit's * `html` already preserves since every adapter stores a unit's own * outer tag, not just its inner text. * * @param array $units ContentUnit stream. * @return string */ protected static function units_html( array $units ): string { return implode( '', array_column( $units, 'html' ) ); } /** * Whether the content has at least one , independent of alt text — * used to decide whether image_alt is applicable at all (see * calculate_score()'s $not_applicable parameter), not whether it passes. * * @param string $content HTML to check. * @return bool */ protected function content_has_images( string $content ): bool { return 1 === preg_match( '/, independent of * internal/external mix — used to decide whether `links` is applicable * at all. A post with one internal link and zero external ones is a * real, actionable fail (has_links stays true); zero links of any kind * is "can't see its subject." * * @param string $content HTML to check. * @return bool */ protected function content_has_links( string $content ): bool { return 1 === preg_match( '/]*\bhref=/i', $content ); } /** * Builds the zero-value result returned when the post doesn't exist or * no focus keyword was supplied. * * @param int $post_id Post ID. * @param string $focus_keyword Focus keyword as passed in (possibly empty). * @return array{post_id:int, focus_keyword:string, content_score:int, content_score_points:int, content_score_max:int, keyword_density:float, checks:array, readability:array, recommendations:array, block_recommendations:array} */ protected function empty_result( int $post_id, string $focus_keyword ): array { return array( 'post_id' => $post_id, 'focus_keyword' => $focus_keyword, 'content_score' => 0, 'content_score_points' => 0, 'content_score_max' => 100, 'keyword_density' => 0.0, 'checks' => array(), 'score_breakdown' => array(), 'readability' => array(), 'recommendations' => array(), 'block_recommendations' => array(), 'content_boundary' => 'raw_content', ); } /** * Whether the keyword appears inside any heading unit at one of the * given levels. P3 component 3 (2026-09-05): reads the ContentUnit * stream directly (kind='heading' filtered by level) instead of a * regex over a raw content string — each unit's own `text` is already * html-stripped/whitespace-normalized by whichever adapter produced * it, so no separate wp_strip_all_tags() step is needed here either. * * "Required input" (2026-09-05 coordinator decision on the applicable- * weights generalization): this method's own required input is simply * "a heading unit at one of $levels exists" — its caller decides * separately whether that absence makes the WHOLE check "not * applicable" (subheadings has no other input, so its absence does — * though subheadings is deliberately kept OUT of * applicable_check_weights()'s exclusion set regardless; see that * method's docblock for why "no other input" doesn't automatically mean * "not applicable" here) or merely means one of two OR'd inputs came * back empty (h1, which always has post_title as its other, * always-available input — see check_h1()). This method itself doesn't * need to know which case it's in; it only ever answers "did this * specific input find a match." * * @param array $units ContentUnit stream. * @param string $keyword Focus keyword (or phrase). * @param int[] $levels Heading levels to check, e.g. [1] or [2..6]. * @return bool True if found in at least one matching heading. */ protected function check_heading_group( array $units, string $keyword, array $levels ): bool { foreach ( $units as $unit ) { if ( 'heading' !== $unit['kind'] || ! in_array( $unit['level'], $levels, true ) ) { continue; } if ( $this->keywords->contains( $unit['text'], $keyword ) ) { return true; } } return false; } /** * Whether the focus keyword is in the page's real, rendered H1. In * WordPress that's `post_title` — themes render it as the page/post H1 * from the template, not from a block inside post_content — so this * checks $post_title first. A literal `

` inside the content itself * is checked too (an OR, not instead-of): rare in standard themes, but * some page builders / custom templates do render one, and if an author * put the keyword there it should still count. * * Replaces the pre-A5 version, which only ever looked for a literal * `

` in post_content — a check that could never pass on a normal * WordPress theme regardless of content quality (see * ABDS-SEO-TZ-SCORE-WOW-093.md Task A, finding 01). * * "Required/optional input" (2026-09-05): post_title is this check's * REQUIRED input — always available, so h1 is never "not applicable" * regardless of the content-unit stream. heading(level=1) is OPTIONAL * — its absence from the stream just means that OR-branch contributes * nothing, not that the whole check stops being evaluable. This is why * h1 was never, and still isn't, part of applicable_check_weights()'s * exclusion set the way image_alt/links are. * * @param string $post_title The post's actual title (not the overridable SEO title). * @param array $units ContentUnit stream. * @param string $keyword Focus keyword (or phrase). * @return bool True if the keyword is in post_title or an explicit content

. */ protected function check_h1( string $post_title, array $units, string $keyword ): bool { if ( $this->keywords->contains( $post_title, $keyword ) ) { return true; } return $this->check_heading_group( $units, $keyword, array( 1 ) ); } /** * Whether the focus keyword appears in the URL slug. For Cyrillic (and * other non-ASCII) keywords this needs two extra comparisons beyond a * literal match, because of how WordPress actually stores non-Latin * slugs — NOT by transliterating to Latin (a wrong assumption corrected * during Task A5's implementation; sanitize_title() percent-encodes the * UTF-8 bytes instead, e.g. "стиснення" becomes "%d1%81%d1%82..."): * * 1. $post->post_name in the database is itself percent-encoded for a * Cyrillic title, so it needs urldecode() before a literal keyword * match can work at all. * 2. As a defensive fallback (a manually-typed Latin slug, a filter * that changes the encoding), sanitize_title($keyword) is compared * against the raw, still-encoded slug too — both sides go through * the same percent-encoding, so they stay comparable. * * Real-world confirmation: this was ABDS-SEO-TZ-SCORE-WOW-093.md Task A * finding 02, originally diagnosed as "Yoast/Rank Math share this gap * too" — true only for a hand-typed Latin slug; WordPress's actual * default Cyrillic-slug behavior is fixable outright, and doing so is * a real advantage this plugin now has that neither competitor does. * * sanitize_title() is a WordPress function, so this method lives here * rather than in ABDS_SEO_Keyword_Extractor, which stays free of WP * calls for unit testing without bootstrapping WP. * * @param string $slug URL slug to check. * @param string $keyword Focus keyword (or phrase). * @return bool True if the slug contains the keyword in any of the forms above. */ protected function check_slug( string $slug, string $keyword ): bool { if ( $this->keywords->slug_contains_keyword( $slug, $keyword ) ) { return true; } $decoded_slug = urldecode( $slug ); if ( $decoded_slug !== $slug && $this->keywords->slug_contains_keyword( $decoded_slug, $keyword ) ) { return true; } return $this->keywords->slug_contains_keyword( $slug, sanitize_title( $keyword ) ); } /** * Whether at least one image unit's alt text contains the focus * keyword. Matches Yoast's imageKeyphrase / Rank Math's * keywordInImageAlt checks (ABDS-SEO-TZ-SCORE-WOW-093.md Task A5 item * 4) — a page with zero images fails this the same way a page with * images-but-no-matching-alt does, consistent with both competitors * (whether it's excluded from the score's denominator entirely, rather * than counted as a fail, is applicable_check_weights()'s own separate * decision — this method only ever answers "does a match exist"). * * P3 component 3 (2026-09-05): reads image units directly instead of a * regex over a raw content string. The alt-attribute extraction itself * stays a small per-unit regex against that unit's own `html` (exactly * one tag) — required input is "image units exist" (see * applicable_check_weights()'s content_has_images()), not something * this method itself needs to special-case. * * @param array $units ContentUnit stream. * @param string $keyword Focus keyword (or phrase). * @return bool True if a matching alt text is found. */ protected function check_image_alt( array $units, string $keyword ): bool { foreach ( $units as $unit ) { if ( 'image' !== $unit['kind'] ) { continue; } if ( ! preg_match( '/\balt=(["\'])(.*?)\1/is', $unit['html'], $match ) ) { continue; } if ( $this->keywords->contains( html_entity_decode( $match[2] ), $keyword ) ) { return true; } } return false; } /** * Whether the content has at least one internal link (same host, or a * relative URL) AND at least one external link (a different host). * Kept as a single combined check per Task A5 item 4's explicit "3 * checks" scope (image alt / links / content length) rather than * splitting into two separately-weighted checks the way Yoast/Rank Math * do — a cheaper first cut; splitting these into their own weights is * open for R3, where the checks are being refactored onto * AuditCheckInterface anyway. * * P3 component 3 (2026-09-05): scans the SAME concatenated unit html * ABDS_SEO_Readability_Checker::analyze() reads (self::units_html()), * not a filtered subset — an image unit can never contain a link (its * own html is just the bare tag), so excluding image units from * this scan would be an optimization, not a correctness requirement; * simpler to have one fewer special case and just scan everything. * * @param array $units ContentUnit stream. * @return bool True if both an internal and an external link are present. */ protected function check_links( array $units ): bool { $content = self::units_html( $units ); if ( ! preg_match_all( '/]*\bhref=(["\'])(.*?)\1/is', $content, $matches ) ) { return false; } $site_host = (string) wp_parse_url( home_url(), PHP_URL_HOST ); $has_internal = false; $has_external = false; foreach ( $matches[2] as $href ) { $href = html_entity_decode( $href ); if ( '' === $href || '#' === $href[0] ) { continue; } $link_host = wp_parse_url( $href, PHP_URL_HOST ); if ( empty( $link_host ) || $link_host === $site_host ) { $has_internal = true; } else { $has_external = true; } } return $has_internal && $has_external; } /** * Builds the add/adapt/remove recommendation list from the check * results and keyword density, then ties each to a Gutenberg block. * * @param array $checks Placement check results, keyed by check name. * @param float $density Keyword density percentage. * @param string $content Post content HTML. * @return array */ protected function build_recommendations( array $checks, float $density, string $content ): array { $recommendations = array(); if ( ! $checks['title'] ) { $recommendations[] = $this->recommendation( self::ACTION_ADAPT, 'title', __( 'Add the focus keyword to the page title.', 'abds-seo' ) ); } if ( ! $checks['h1'] ) { $recommendations[] = $this->recommendation( self::ACTION_ADD, 'h1', __( 'Add the focus keyword to the H1 heading.', 'abds-seo' ) ); } if ( ! $checks['first_100_words'] ) { $recommendations[] = $this->recommendation( self::ACTION_ADAPT, 'first_paragraph', __( 'Mention the keyword in the first 100 words of the text.', 'abds-seo' ) ); } if ( ! $checks['subheadings'] ) { $recommendations[] = $this->recommendation( self::ACTION_ADD, 'subheading', __( 'Add a subheading (H2–H6) with the keyword or a variation of it.', 'abds-seo' ) ); } if ( ! $checks['meta_description'] ) { $recommendations[] = $this->recommendation( self::ACTION_ADD, 'meta_description', __( 'Add a meta description containing the keyword.', 'abds-seo' ) ); } if ( ! $checks['slug'] ) { $recommendations[] = $this->recommendation( self::ACTION_ADAPT, 'slug', __( 'Consider adding the keyword to the URL slug.', 'abds-seo' ) ); } if ( ! $checks['image_alt'] ) { $recommendations[] = $this->recommendation( self::ACTION_ADD, 'image_alt', __( 'Add an image with the focus keyword in its alt text.', 'abds-seo' ) ); } if ( ! $checks['links'] ) { $recommendations[] = $this->recommendation( self::ACTION_ADD, 'links', __( 'Add at least one internal link and one link to an external source.', 'abds-seo' ) ); } if ( ! $checks['content_length'] ) { $recommendations[] = $this->recommendation( self::ACTION_ADAPT, 'content_length', sprintf( /* translators: %d: minimum recommended word count. */ __( 'This page is under %d words — consider expanding it.', 'abds-seo' ), self::MIN_CONTENT_WORDS ) ); } if ( $density > self::DENSITY_MAX ) { $recommendations[] = $this->recommendation( self::ACTION_REMOVE, 'content', sprintf( /* translators: %s: keyword density percentage. */ __( 'Keyword over-stuffing (density %s%%) — remove some repetitions.', 'abds-seo' ), $density ) ); } elseif ( $density < self::DENSITY_MIN ) { $recommendations[] = $this->recommendation( self::ACTION_ADAPT, 'content', sprintf( /* translators: %s: keyword density percentage. */ __( 'Keyword density is too low (%s%%) — add a few natural mentions in the text.', 'abds-seo' ), $density ) ); } return $this->attach_block_references( $recommendations, $content ); } /** * Builds a single recommendation entry. * * @param string $action One of the ACTION_* constants. * @param string $target Recommendation target, e.g. "title", "h1", "content". * @param string $message Human-readable, translated message. * @return array{action:string, target:string, message:string, block_client_id:?string, block_position:?int} */ protected function recommendation( string $action, string $target, string $message ): array { return array( 'action' => $action, 'target' => $target, 'message' => $message, 'block_client_id' => null, 'block_position' => null, ); } /** * Ties a recommendation to the Gutenberg block it applies to. Server-side * parse_blocks() does not expose the editor's runtime clientId, so the * block's position in the post is used as the fallback identifier — the * REST layer can be called from the editor with the live clientId when * a richer match is available (see includes/api/class-abds-seo-rest-controller.php). * * @param array $recommendations Recommendations to annotate. * @param string $content Post content HTML. * @return array */ protected function attach_block_references( array $recommendations, string $content ): array { if ( ! function_exists( 'parse_blocks' ) ) { return $recommendations; } $blocks = parse_blocks( $content ); $block_map = array( 'h1' => 'core/heading', 'subheading' => 'core/heading', 'first_paragraph' => 'core/paragraph', 'image_alt' => 'core/image', ); foreach ( $recommendations as &$recommendation ) { $wanted_block_name = $block_map[ $recommendation['target'] ] ?? null; if ( ! $wanted_block_name ) { continue; } foreach ( $blocks as $position => $block ) { if ( ( $block['blockName'] ?? null ) === $wanted_block_name ) { $recommendation['block_position'] = $position; break; } } } unset( $recommendation ); return $recommendations; } /** * Maps a single ABDS_SEO_Block_Recommendations entry's machine-readable * "issue" code to a translated "suggestion" message. Kept here, in the * WP-dependent orchestrator, rather than in ABDS_SEO_Block_Recommendations * itself, because that class calls zero WordPress functions (including * __()) so it stays unit testable without bootstrapping WP. * * @param array{block_ref:string, block_type:string, content_snippet:string, issue:string, severity:string} $recommendation Entry from ABDS_SEO_Block_Recommendations::analyze(). * @return array{block_ref:string, block_type:string, content_snippet:string, issue:string, suggestion:string, severity:string} */ protected function translate_block_recommendation( array $recommendation ): array { $messages = array( 'heading_missing_keyword' => __( 'Add the focus keyword to this subheading.', 'abds-seo' ), 'first_paragraph_missing_keyword' => __( 'The first paragraph does not contain the focus keyword.', 'abds-seo' ), 'paragraph_too_long' => __( 'This paragraph is too long — split it for better readability.', 'abds-seo' ), 'image_missing_alt' => __( 'This image has no alt text.', 'abds-seo' ), 'list_empty' => __( 'This list is empty.', 'abds-seo' ), ); $recommendation['suggestion'] = $messages[ $recommendation['issue'] ] ?? ''; return $recommendation; } /** * Categorizes a content_score into good/ok/poor/not_analyzed — the one * place this plugin decides what those words mean, reused everywhere * a score needs a traffic-light-style label (currently: reports, see * ABDS_SEO_Reports) rather than each caller re-deriving its own * boundaries. Deliberately reuses abds_seo_prepublish_threshold (see * ABDS_SEO_Rest_Controller::get_content_analysis()) as the poor/ok * boundary instead of a second constant, so "below the pre-publish * warning threshold" and "poor" always mean the same score, not two * numbers that could drift apart. * * @param ?int $score Content score, 0-100, or null if never analyzed. * @return string 'good', 'ok', 'poor', or 'not_analyzed'. */ public static function categorize_score( ?int $score ): string { if ( null === $score ) { return 'not_analyzed'; } /** This filter is documented in includes/api/class-abds-seo-rest-controller.php. */ $poor_threshold = (int) apply_filters( 'abds_seo_prepublish_threshold', 60 ); /** * Filters the content_score at/above which a page is categorized * "good" rather than "ok". Like abds_seo_prepublish_threshold, a * starting heuristic meant to be recalibrated once real usage data * exists. * * @param int $threshold Minimum content_score (0-100) for "good". Default 80. */ $good_threshold = (int) apply_filters( 'abds_seo_good_score_threshold', 80 ); if ( $score >= $good_threshold ) { return 'good'; } if ( $score >= $poor_threshold ) { return 'ok'; } return 'poor'; } /** * Combines weighted check results, density fit, and readability into a * 0-100 content score. Each check contributes its own CHECK_WEIGHTS * point value when passed (replacing the pre-A5 equal 1/6 split, see * CHECK_WEIGHTS's docblock) rather than the old flat percentage-of- * passed-checks model. * * $applicable_weights (P3, 2026-09-04, normalization revised 2026-09-05) * is CHECK_WEIGHTS with any inapplicable check's own weight genuinely * removed — a check that can't see its subject (image_alt with zero * images in the analyzed content, links with zero links) is excluded * from the score's own denominator, not credited as if passed. Computed * ONCE in compute() (applicable_check_weights()) and passed into both * this method and build_score_breakdown(), so the two can never * independently drift on what "applicable" means. * * The RETURNED content_score is normalized to 0-100 here — the one * place this score is born — precisely so no consumer needs to know * `max` ever varies: categorize_score(), the pre-publish threshold, the * post-list badge, and ABDS_SEO_Reports all keep reading a plain 0-100 * number with the SAME meaning it always had, unchanged. An earlier * version of this method left the raw sum unnormalized (content_score's * own ceiling dropping below 100 for a post lacking images/links) and * pushed the "normalize to compare across posts" burden onto every * reader instead — rejected: readers should never have to know. * * For the common case — both image_alt and links applicable — `max` * (array_sum($applicable_weights) + DENSITY_WEIGHT + READABILITY_WEIGHT) * is exactly 100, so normalizing (raw_points / 100 * 100) is * mathematically the identity on the already-integer raw_points: this * method returns EXACTLY what it did before this normalization step * existed, not a differently-rounded number. The A5/A6 calibration * (ABDS-SEO-TZ-SCORE-WOW-093.md) is untouched for every post where both * checks can see their subject. * * NO MIGRATION of previously-stored wp_abds_seo_page_scores.content_score * values was done for this normalization change (coordinator decision, * 2026-09-05) — a value stored before this method normalized (or stored * under the earlier, since-replaced full-credit reading) was computed * under a different model and is simply stale, the same way any change * to CHECK_WEIGHTS/DENSITY_WEIGHT/READABILITY_WEIGHT has always made * older stored scores stale without a migration. It self-corrects the * next time analyze() runs for that post (save_post, or the background * ABDS_SEO_Content_Score_Cache job) — a post's displayed score jumping * on its next save is expected here, not evidence of a bug. * * @param array $checks Placement check results, keyed by check name. * @param float $density Keyword density percentage. * @param int $readability_score Readability sub-score, 0-100. * @param array $applicable_weights CHECK_WEIGHTS filtered to applicable checks — see applicable_check_weights(). * @return array{score:int, raw_points:int, max:int} `score` is the normalized * 0-100 content_score; `raw_points`/`max` are the UNnormalized * earned/possible totals build_score_breakdown()'s own rows sum * to — kept only so a caller can show "70 of 87 points" next to * the normalized score, per compute()'s content_score_max. */ protected function calculate_score( array $checks, float $density, int $readability_score, array $applicable_weights ): array { $checks_score = 0; foreach ( $checks as $key => $passed ) { if ( $passed && isset( $applicable_weights[ $key ] ) ) { $checks_score += $applicable_weights[ $key ]; } } $density_score = ( $density >= self::DENSITY_MIN && $density <= self::DENSITY_MAX ) ? self::DENSITY_WEIGHT : self::DENSITY_WEIGHT / 2; $readability_weighted = ( $readability_score / 100 ) * self::READABILITY_WEIGHT; $raw_points = (int) round( $checks_score + $density_score + $readability_weighted ); $max = array_sum( $applicable_weights ) + self::DENSITY_WEIGHT + self::READABILITY_WEIGHT; $score = $max > 0 ? (int) round( ( $raw_points / $max ) * 100 ) : 0; return array( 'score' => $score, 'raw_points' => $raw_points, 'max' => $max, ); } /** * Builds the "what the score is made of" breakdown shown next to the * score in both editors (Task A6, ABDS-SEO-TZ-SCORE-WOW-093.md) — one * row per scoring input with its earned/possible points, in the exact * same units calculate_score() adds together, so the UI can never * silently drift out of sync with the actual formula. A bridge to the * R3 severity system: same shape (item, verdict, contribution) as the * planned audit-check breakdown, just scoped to content-score inputs * for now. * * Density and readability aren't boolean pass/fail like the CHECK_WEIGHTS * items — density is half-credit outside its ideal range rather than * zero, and readability scales smoothly — so both are represented the * same way as the boolean checks (points earned out of max) rather than * forcing an artificial pass/fail flag onto them; the UI derives a * checkmark/partial/empty state from points === max / points > 0 / 0. * * @param array $checks Placement check results, keyed by check name. * @param float $density Keyword density percentage. * @param int $readability_score Readability sub-score, 0-100. * @param array $applicable_weights CHECK_WEIGHTS filtered to applicable checks — * the SAME array calculate_score() was given, see * that method's docblock for why a shared, once- * computed array (not two independent * calculations) is what actually solves the drift * risk between this method and that one. * @return array */ protected function build_score_breakdown( array $checks, float $density, int $readability_score, array $applicable_weights ): array { $labels = array( 'title' => __( 'Keyword in the SEO title', 'abds-seo' ), 'h1' => __( 'Keyword in the H1 (page title)', 'abds-seo' ), 'first_100_words' => __( 'Keyword in the first 100 words', 'abds-seo' ), 'subheadings' => __( 'Keyword in a subheading', 'abds-seo' ), 'meta_description' => __( 'Keyword in the meta description', 'abds-seo' ), 'slug' => __( 'Keyword in the URL slug', 'abds-seo' ), 'image_alt' => __( 'Keyword in an image alt text', 'abds-seo' ), 'links' => __( 'Internal and external links', 'abds-seo' ), 'content_length' => __( 'Content length', 'abds-seo' ), ); $not_applicable_notes = array( 'image_alt' => __( 'Not checked — no images found in the analyzed content.', 'abds-seo' ), 'links' => __( 'Not checked — no links found in the analyzed content.', 'abds-seo' ), ); $breakdown = array(); foreach ( $checks as $key => $passed ) { $applicable = isset( $applicable_weights[ $key ] ); $max = $applicable ? $applicable_weights[ $key ] : 0; $breakdown[] = array( 'key' => $key, 'label' => $labels[ $key ] ?? $key, 'points' => ( $passed && $applicable ) ? $max : 0, 'max_points' => $max, 'applicable' => $applicable, 'note' => $applicable ? '' : ( $not_applicable_notes[ $key ] ?? '' ), ); } $density_in_range = ( $density >= self::DENSITY_MIN && $density <= self::DENSITY_MAX ); $breakdown[] = array( 'key' => 'density', 'label' => __( 'Keyword density in the ideal range', 'abds-seo' ), 'points' => $density_in_range ? self::DENSITY_WEIGHT : (int) ( self::DENSITY_WEIGHT / 2 ), 'max_points' => self::DENSITY_WEIGHT, 'applicable' => true, 'note' => '', ); $breakdown[] = array( 'key' => 'readability', 'label' => __( 'Readability', 'abds-seo' ), 'points' => (int) round( ( $readability_score / 100 ) * self::READABILITY_WEIGHT ), 'max_points' => self::READABILITY_WEIGHT, 'applicable' => true, 'note' => '', ); return $breakdown; } /** * Upserts the content score and recommendations into wp_abds_seo_page_scores. * * $score may be null (P3, 2026-09-04): the content-boundary fetch found * nothing to analyze at all (compute()'s unavailable_result()) — the * `content_score` column is DECIMAL(5,2) NULL for exactly this "not * really analyzed" case, same as a post that was never scored, * matching categorize_score(null) => 'not_analyzed'. $wpdb's own insert()/ * update() write a literal SQL NULL for a null value regardless of the * '%f' format placeholder, so no special-casing is needed here beyond * accepting the nullable type. * * @param int $post_id Post ID. * @param ?int $score Content score, 0 to content_score_max, or null (not analyzable). * @param array $recommendations Recommendations to store. */ protected function persist_result( int $post_id, ?int $score, array $recommendations ): void { global $wpdb; $table = $wpdb->prefix . 'abds_seo_page_scores'; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- $table is built only from $wpdb->prefix plus a hardcoded literal, never user input; $post_id is passed through $wpdb->prepare(). Runs once per editor keystroke-debounced analysis request, not a cacheable read path. $existing_id = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM {$table} WHERE post_id = %d", $post_id ) ); // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter -- $table is built only from $wpdb->prefix plus a hardcoded literal, never user input; $wpdb->update()/insert() safely escape their values via the format array. Runs once per editor keystroke-debounced analysis request, not a cacheable read path. if ( $existing_id ) { $wpdb->update( $table, array( 'content_score' => $score, 'last_scanned' => current_time( 'mysql' ), ), array( 'id' => $existing_id ), array( '%f', '%s' ), array( '%d' ) ); } else { $wpdb->insert( $table, array( 'post_id' => $post_id, 'content_score' => $score, 'issues_json' => wp_json_encode( array( 'content_recommendations' => $recommendations ) ), 'last_scanned' => current_time( 'mysql' ), ), array( '%d', '%f', '%s', '%s' ) ); } // phpcs:enable } }