*/ public static function groups(): array { return array( 'shorttail', 'longtail', 'geo' ); } /** * Stored keywords for a post, always shaped as all three groups. * * @return array> */ public static function get( int $post_id ): array { $stored = get_post_meta( $post_id, self::META_KEY, true ); $out = array(); foreach ( self::groups() as $group ) { $list = is_array( $stored ) && isset( $stored[ $group ] ) ? (array) $stored[ $group ] : array(); $out[ $group ] = array_values( array_filter( array_map( 'strval', $list ) ) ); } // Migrate a legacy single focus keyword into the short-tail group. if ( empty( $out['shorttail'] ) ) { $legacy = trim( (string) get_post_meta( $post_id, '_airanksuite_focus_keyword', true ) ); if ( '' !== $legacy ) { $out['shorttail'] = array( $legacy ); } } // Still nothing of our own: show what the previous SEO plugin knew, // read on the fly. The editor and every score then work with those // keywords the moment this plugin is activated; the importer makes // them ours permanently, and a save writes them under our key. if ( empty( $out['shorttail'] ) ) { $out['shorttail'] = self::from_other_plugins( $post_id ); } return $out; } /** * Focus keywords another SEO plugin stored for this post. * * @return array */ public static function from_other_plugins( int $post_id ): array { $list = array(); foreach ( array( 'rank_math_focus_keyword', '_yoast_wpseo_focuskw', '_seopress_analysis_target_kw', '_genesis_keywords', '_aioseo_keyphrases' ) as $key ) { $raw = get_post_meta( $post_id, $key, true ); if ( '_aioseo_keyphrases' === $key ) { $decoded = is_string( $raw ) ? json_decode( $raw, true ) : ( is_array( $raw ) ? $raw : null ); if ( is_array( $decoded ) ) { if ( ! empty( $decoded['focus']['keyphrase'] ) ) { $list[] = (string) $decoded['focus']['keyphrase']; } foreach ( (array) ( $decoded['additional'] ?? array() ) as $a ) { if ( ! empty( $a['keyphrase'] ) ) { $list[] = (string) $a['keyphrase']; } } } continue; } if ( is_string( $raw ) && '' !== trim( $raw ) ) { foreach ( explode( ',', $raw ) as $k ) { $list[] = trim( $k ); } } if ( '_yoast_wpseo_focuskw' === $key ) { $related = get_post_meta( $post_id, '_yoast_wpseo_focuskeywords', true ); $decoded = is_string( $related ) && '' !== $related ? json_decode( $related, true ) : null; foreach ( (array) $decoded as $r ) { if ( is_array( $r ) && ! empty( $r['keyword'] ) ) { $list[] = trim( (string) $r['keyword'] ); } } } } $list = array_values( array_unique( array_filter( array_map( 'sanitize_text_field', $list ) ) ) ); return array_slice( $list, 0, self::MAX_PER_GROUP ); } /** * Persist keywords (deduplicated, trimmed, capped). * * @param array $input Raw input per group. * @return array> */ public static function save( int $post_id, array $input ): array { // Start from what is already stored, not from empty. // // The metabox and the editor sidebar only ever send `shorttail`. With a // blank start, every save from either of them silently wiped the // long-tail keywords and AI prompts entered in the full editor — the // keywords were "not saved" because a later save from a different // screen had deleted them. A group absent from the payload means "not // edited here", never "empty". $clean = self::get( $post_id ); foreach ( self::groups() as $group ) { if ( ! array_key_exists( $group, $input ) ) { continue; } $list = $input[ $group ]; if ( is_string( $list ) ) { $list = preg_split( '/\r\n|\r|\n|,/', $list ) ?: array(); } $seen = array(); foreach ( (array) $list as $keyword ) { $keyword = trim( sanitize_text_field( (string) $keyword ) ); if ( '' === $keyword || mb_strlen( $keyword ) > 191 ) { continue; } $key = self::lower( $keyword ); if ( isset( $seen[ $key ] ) ) { continue; } $seen[ $key ] = $keyword; if ( count( $seen ) >= self::MAX_PER_GROUP ) { break; } } $clean[ $group ] = array_values( $seen ); } update_post_meta( $post_id, self::META_KEY, $clean ); // Keep the legacy meta in sync so the rank tracker and older code keep working. $primary = $clean['shorttail'][0] ?? ''; if ( '' !== $primary ) { update_post_meta( $post_id, '_airanksuite_focus_keyword', $primary ); } else { delete_post_meta( $post_id, '_airanksuite_focus_keyword' ); } return $clean; } /** * The primary focus keyword (first short-tail entry). */ public static function primary( int $post_id ): string { $keywords = self::get( $post_id ); return (string) ( $keywords['shorttail'][0] ?? '' ); } /** * Coverage matrix for every keyword on the page. * * @param array> $keywords Keywords per group. * @param array $headings Headings. * @param array $paragraphs Paragraphs. * @return array */ public function coverage( WP_Post $post, string $html, array $keywords, array $headings, array $paragraphs ): array { $text = Html::text( $html ); $body = self::lower( $text ); $word_count = max( 1, count( preg_split( '/\s+/u', $text ) ?: array() ) ); // Resolve template variables first — a raw "%title% %sep% %sitename%" // would never contain the keyword even though the rendered title does. $title = self::lower( \AiRankSuite\Modules\Seo\SeoModule::resolve_title( $post ) ); $desc = (string) get_post_meta( $post->ID, '_airanksuite_seo_desc', true ); if ( '' === trim( $desc ) ) { $desc = (string) get_post_meta( $post->ID, '_airanksuite_ai_summary', true ); } if ( '' === trim( $desc ) ) { $desc = (string) $post->post_excerpt; } $desc = self::lower( Html::text( $desc ) ); $slug = self::lower( str_replace( array( '-', '_' ), ' ', (string) $post->post_name ) ); $heading_text = self::lower( implode( ' | ', array_map( static fn( $h ) => $h[1], $headings ) ) ); $alt_text = self::lower( $this->alt_texts( $html ) ); $faq_questions = self::lower( $this->faq_questions( $post ) ); $rows = array(); $summary = array(); foreach ( self::groups() as $group ) { $found = 0; $total = count( $keywords[ $group ] ?? array() ); foreach ( (array) ( $keywords[ $group ] ?? array() ) as $keyword ) { $needle = self::lower( $keyword ); if ( '' === $needle ) { continue; } $row = 'geo' === $group ? $this->geo_row( $keyword, $needle, $body, $heading_text, $faq_questions, $desc, $paragraphs ) : $this->standard_row( $keyword, $needle, $title, $desc, $slug, $heading_text, $body, $alt_text, $word_count ); $row['group'] = $group; $rows[] = $row; if ( $row['score'] >= 50 ) { ++$found; } } $summary[ $group ] = array( 'total' => $total, 'covered' => $found, 'coverage' => $total > 0 ? (int) round( 100 * $found / $total ) : 0, ); } usort( $rows, static fn( $a, $b ) => $a['score'] <=> $b['score'] ); return array( 'rows' => $rows, 'summary' => $summary, ); } /** * Coverage of a normal (short-tail / long-tail) keyword. * * @return array */ private function standard_row( string $keyword, string $needle, string $title, string $desc, string $slug, string $headings, string $body, string $alt, int $word_count ): array { $occurrences = substr_count( $body, $needle ); // Density = phrase occurrences per hundred words — the same definition // the density check uses. It used to multiply by the number of words in // the phrase, so a three-word keyword showed 37% here and 9% in the // check beside it, and the "read as stuffing" verdict fired on pages // that were fine. $density = $word_count > 0 ? round( ( $occurrences / $word_count ) * 100, 2 ) : 0.0; $signals = array( 'title' => str_contains( $title, $needle ), 'desc' => str_contains( $desc, $needle ), 'url' => str_contains( $slug, $needle ), 'heading' => str_contains( $headings, $needle ), 'body' => $occurrences > 0, 'alt' => str_contains( $alt, $needle ), ); // Weighted: appearing in the body at all matters most, then title/heading. $weights = array( 'body' => 30, 'title' => 25, 'heading' => 20, 'desc' => 12, 'url' => 8, 'alt' => 5, ); $score = 0; foreach ( $weights as $key => $weight ) { if ( $signals[ $key ] ) { $score += $weight; } } return array( 'keyword' => $keyword, 'signals' => $signals, 'occurrences' => $occurrences, 'density' => $density, 'score' => min( 100, $score ), ); } /** * Coverage of a GEO prompt — a question someone would ask an AI assistant. * * @param array $paragraphs Paragraphs. * @return array */ private function geo_row( string $keyword, string $needle, string $body, string $headings, string $faq_questions, string $desc, array $paragraphs ): array { // Prompts are phrased as questions, so exact matching rarely works. // Score on the share of meaningful terms that appear, plus answer signals. $terms = array_values( array_filter( preg_split( '/[^\p{L}\p{N}]+/u', $needle, -1, PREG_SPLIT_NO_EMPTY ) ?: array(), static fn( $t ) => mb_strlen( $t ) >= 4 ) ); if ( empty( $terms ) ) { $terms = array( $needle ); } $hits = 0; foreach ( $terms as $term ) { if ( str_contains( $body, $term ) ) { ++$hits; } } $term_ratio = $hits / count( $terms ); $in_heading = false; $in_answer = false; foreach ( $terms as $term ) { if ( str_contains( $headings, $term ) ) { $in_heading = true; break; } } // A self-contained answer: a paragraph carrying most terms and ≥ 25 words. foreach ( $paragraphs as $paragraph ) { $lower = self::lower( $paragraph ); $matched = 0; foreach ( $terms as $term ) { if ( str_contains( $lower, $term ) ) { ++$matched; } } if ( $matched / count( $terms ) >= 0.6 && count( preg_split( '/\s+/u', $paragraph ) ?: array() ) >= 25 ) { $in_answer = true; break; } } $in_faq = false; $faq_needle = trim( (string) preg_replace( '/[^\p{L}\p{N}\s]/u', '', $needle ) ); if ( '' !== $faq_needle && str_contains( $faq_questions, mb_substr( $faq_needle, 0, 40 ) ) ) { $in_faq = true; } $score = (int) round( 40 * $term_ratio ); if ( $in_answer ) { $score += 30; } if ( $in_heading ) { $score += 20; } if ( $in_faq ) { $score += 10; } return array( 'keyword' => $keyword, 'signals' => array( 'terms' => $term_ratio >= 0.6, 'answer' => $in_answer, 'heading' => $in_heading, 'faq' => $in_faq, 'desc' => str_contains( $desc, mb_substr( $needle, 0, 30 ) ), ), 'occurrences' => $hits, 'density' => round( 100 * $term_ratio, 1 ), 'score' => min( 100, $score ), ); } private function alt_texts( string $html ): string { $out = array(); if ( preg_match_all( '/alt\s*=\s*("([^"]*)"|\'([^\']*)\')/i', $html, $m ) ) { foreach ( $m[2] as $i => $alt ) { $out[] = '' !== $alt ? $alt : $m[3][ $i ]; } } return implode( ' | ', $out ); } private function faq_questions( WP_Post $post ): string { $raw = get_post_meta( $post->ID, '_airanksuite_faq', true ); if ( ! is_string( $raw ) || '' === $raw ) { return ''; } $faqs = json_decode( $raw, true ); if ( ! is_array( $faqs ) ) { return ''; } $out = array(); foreach ( $faqs as $faq ) { $out[] = (string) preg_replace( '/[^\p{L}\p{N}\s]/u', '', (string) ( $faq['question'] ?? '' ) ); } return implode( ' | ', $out ); } private static function lower( string $value ): string { return function_exists( 'mb_strtolower' ) ? mb_strtolower( $value, 'UTF-8' ) : strtolower( $value ); } }