*/ private array $resolvedTitleMemo = []; /** * Memoized resolved descriptions keyed by context hash. * * Performance optimization: avoids re-evaluating description template replacement and fallback * evaluation chains across render() and renderTwitterTags() in a single request. * * @var array */ private array $resolvedDescriptionMemo = []; /** * Constructor. * * @param SettingsStore $settings Settings store. * @param TagsReplacer|null $replacer Optional replacer. * @param Context|null $context Optional pre-built context (for tests). * @param WP_Query|null $query Optional query (for tests). */ public function __construct( SettingsStore $settings, ?TagsReplacer $replacer = null, ?Context $context = null, ?WP_Query $query = null ) { $this->settings = $settings; $this->replacer = $replacer ?? new TagsReplacer(); $this->injectedContext = $context; $this->injectedQuery = $query; } /** * Register hooks. */ public function boot(): void { add_action( 'wp_head', [ $this, 'render' ], 1 ); add_filter( 'pre_get_document_title', [ $this, 'title' ], 10 ); // Core adds rel_canonical at wp_head 10. RankKernel owns the canonical for // every context it renders, so core must not emit a second, conflicting one. remove_action( 'wp_head', 'rel_canonical' ); // Core owns the single robots tag through wp_robots. RankKernel contributes // directives through that filter instead of echoing its own tag, so there is // exactly one tag, core defaults survive, and other plugins still merge. // Priority 99 runs last so RankKernel's restrictive wins. add_filter( 'wp_robots', [ $this, 'filterRobots' ], 99 ); } /** * Resolve document title. * * @param mixed $title WP-computed title passed to the filter. * @return mixed Resolved title or original unchanged. */ public function title( mixed $title ): mixed { $ctx = $this->getContext(); // Previews are not indexable URLs, return WP default untouched. if ( 'preview' === $ctx->queriedType() ) { return $title; } $resolved = $this->resolveTitlePayloadOrTemplate( $ctx ); if ( null !== $resolved ) { return $resolved; } // Fall back to WP default, never return '' which would break themes. return $title; } /** * Helper to resolve title from payload or template with memoization. * * Performance optimization: memoizes resolved title by Context hash and aligns field keys * ('title', 'title_template') so TagsReplacer memo achieves 100% hits across passes. * Returns null on fallback so title() and getResolvedTitle() apply their distinct fallbacks. * * @param Context $ctx Request context. * @return string|null Resolved title string or null. */ private function resolveTitlePayloadOrTemplate( Context $ctx ): ?string { $hash = $ctx->hash(); if ( array_key_exists( $hash, $this->resolvedTitleMemo ) ) { return $this->resolvedTitleMemo[ $hash ]; } $meta = $ctx->meta(); $payloadTitle = isset( $meta['title'] ) ? trim( (string) $meta['title'] ) : ''; // Payload title takes precedence. if ( '' !== $payloadTitle ) { // Treat raw payload title as literal; resolve ONLY if it contains a token. if ( 1 === preg_match( '/%%[a-z_]+%%/', $payloadTitle ) ) { $resolved = $this->replacer->replace( $ctx, $payloadTitle, 'title' ); if ( '' !== trim( $resolved ) ) { $this->resolvedTitleMemo[ $hash ] = $resolved; return $resolved; } } else { $this->resolvedTitleMemo[ $hash ] = $payloadTitle; return $payloadTitle; } } // Settings template fallback. $template = (string) $this->settings->get( 'title_template', '%%title%% %%sep%% %%sitename%%' ); if ( '' !== trim( $template ) ) { $resolved = $this->normalizeTemplateEdges( $this->replacer->replace( $ctx, $template, 'title_template' ) ); if ( '' !== trim( $resolved ) ) { $this->resolvedTitleMemo[ $hash ] = $resolved; return $resolved; } } return null; } /** * Trim separator and whitespace left at either end of a resolved template. * * A token that resolves to nothing, %%title%% on a date or search archive * for example, would otherwise leave the template's own separator stranded * at the front of the document title, and core never gets to fall back to * its own archive title because a non empty value was returned. * * @param string $resolved Resolved template string. * @return string Trimmed string. */ private function normalizeTemplateEdges( string $resolved ): string { $value = trim( $resolved ); if ( '' === $value ) { return ''; } $separator = $this->settings->get( 'separator', '' ); // The trim target has to be the same string the %%sep%% token rendered, // or the strip silently misses and the stranded mark comes back. // SettingsStore::defaults() sets an en dash, and Context::separator() // falls back to that same en dash for a value that is not a string, so // a different fallback here would aim the trim at a character that is // not the one sitting in the title. $separator = is_string( $separator ) ? trim( $separator ) : '–'; if ( '' !== $separator ) { $value = self::stripStrandedSeparator( $value, $separator, true ); $value = self::stripStrandedSeparator( $value, $separator, false ); $value = trim( $value ); } return trim( preg_replace( '/\s{2,}/', ' ', $value ) ?? $value ); } /** * Strip one separator from an edge, but only where it stands alone. * * The trim function takes a character set, so a multi character separator * ate any matching letter off a legitimate title edge. The comparison is on * whole substrings rather than characters, which keeps a multibyte * separator intact because only complete sequences are ever cut. * * A separator is only stranded when whitespace or the edge of the string * sits on its other side, since that is the shape a template leaves * behind. Requiring it also keeps a separator of 'ab' from eating the * first two letters of a title such as 'abacus'. * * @param string $value Resolved value. * @param string $separator Separator to remove. * @param bool $leading True for the front edge, false for the back edge. * @return string Value with at most one separator removed. */ private static function stripStrandedSeparator( string $value, string $separator, bool $leading ): string { $length = strlen( $separator ); if ( 0 === $length ) { return $value; } if ( $leading ) { if ( 0 !== strncmp( $value, $separator, $length ) ) { return $value; } $after = substr( $value, $length ); if ( '' !== $after && 1 !== preg_match( '/^\s/', $after ) ) { return $value; } return $after; } if ( ! str_ends_with( $value, $separator ) ) { return $value; } $before = substr( $value, 0, -$length ); if ( '' !== $before && 1 !== preg_match( '/\s$/', $before ) ) { return $value; } return $before; } /** * Emit all head tags in ONE pass. */ public function render(): void { // Previews are not indexable URLs, emit no SEO tags. $ctxEarly = $this->getContext(); if ( 'preview' === $ctxEarly->queriedType() ) { return; } // Password-protected posts: title + noindex only, matching schema suppression. if ( $ctxEarly->queriedId() > 0 && function_exists( 'post_password_required' ) && post_password_required( $ctxEarly->queriedId() ) ) { return; } // Feed pages: skip all tags (return early). if ( function_exists( 'is_feed' ) && is_feed() ) { return; } $ctx = $ctxEarly; if ( 'feed' === $ctx->queriedType() ) { return; } $meta = $ctx->meta(); // Description. $description = $this->resolveDescription( $ctx, $meta ); if ( '' !== $description ) { echo '' . "\n"; } // Robots are emitted exactly once by core wp_robots, merged in filterRobots(). // Canonical (omitted on search/404). $canonical = $this->resolveCanonical( $ctx, $meta ); if ( '' !== $canonical ) { echo '' . "\n"; } // OG tags. $this->renderOgTags( $ctx, $meta, $description ); // Twitter tags. $this->renderTwitterTags( $ctx, $meta ); // Webmaster verification. $this->renderWebmasterTags(); // R2 slot: after webmaster codes, before R4 comment, fires for Schema module. do_action( 'rankkernel/head/after_tags', $ctx ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores -- public hook name, part of the plugin API, must stay stable. // R3: rel="prev"/"next" intentionally not emitted (Google deprecated 2019). // R4: No dedicated Slack tags, OG + Twitter already cover Slack's unfurler. } /** * Get or build context (once per request, reused by title() and render()). * * @return Context The result. */ private function getContext(): Context { if ( null !== $this->injectedContext ) { return $this->injectedContext; } if ( null !== $this->context ) { return $this->context; } $query = $this->injectedQuery; if ( null === $query ) { global $wp_query; if ( isset( $wp_query ) && $wp_query instanceof WP_Query ) { $query = $wp_query; } else { $query = new WP_Query(); } } $this->context = new Context( $query, $this->settings, $this->replacer ); return $this->context; } /** * Get resolved document title (payload → template → ctx title) without leaking tokens. * * Performance optimization: memoizes the resolved title by Context hash and aligns field keys * ('title', 'title_template') with title() so TagsReplacer memo achieves 100% hits across passes. * * @param Context $ctx Context. * @return string The result. */ private function getResolvedTitle( Context $ctx ): string { $resolved = $this->resolveTitlePayloadOrTemplate( $ctx ); if ( null !== $resolved ) { return $resolved; } return $ctx->title(); } /** * Resolve description with fallback chain. * * Performance optimization: memoizes resolved description by Context hash to avoid * redundant description template evaluation and fallback checks across render passes. * * @param Context $ctx Context. * @param array $meta Meta payload. * @return string The result. */ private function resolveDescription( Context $ctx, array $meta ): string { $hash = $ctx->hash(); $isStdMeta = ( $meta === $ctx->meta() ); if ( $isStdMeta && array_key_exists( $hash, $this->resolvedDescriptionMemo ) ) { return $this->resolvedDescriptionMemo[ $hash ]; } $result = $this->doResolveDescription( $ctx, $meta ); if ( $isStdMeta ) { $this->resolvedDescriptionMemo[ $hash ] = $result; } return $result; } /** * Compute description resolution fallback chain. * * @param Context $ctx Context. * @param array $meta Meta payload. * @return string The result. */ private function doResolveDescription( Context $ctx, array $meta ): string { $desc = isset( $meta['description'] ) ? trim( (string) $meta['description'] ) : ''; if ( '' !== $desc ) { return $desc; } // Settings description template resolved via TagsReplacer. $tpl = (string) $this->settings->get( 'description_template', '' ); if ( '' !== trim( $tpl ) ) { $resolved = $this->replacer->replace( $ctx, $tpl, 'description' ); if ( '' !== trim( $resolved ) ) { return trim( $resolved ); } } // Fallback: trimmed excerpt (singular) / taxonomy description / ''. if ( $ctx->isSingular() ) { $excerpt = $ctx->excerpt(); if ( '' !== $excerpt ) { return $excerpt; } } elseif ( 'term' === $ctx->queriedType() ) { $termDesc = get_term_field( 'description', $ctx->queriedId() ); if ( is_string( $termDesc ) && '' !== trim( $termDesc ) ) { $clean = function_exists( 'wp_strip_all_tags' ) ? wp_strip_all_tags( $termDesc ) : strip_tags( $termDesc ); // phpcs:ignore WordPress.WP.AlternativeFunctions.strip_tags_strip_tags -- strip_tags fallback preserves inner text where wp_kses_post and wp_strip_all_tags are unavailable, matching the MetaPayload fallback. return trim( $clean ); } if ( ! is_wp_error( $termDesc ) && is_string( $termDesc ) ) { return trim( $termDesc ); } } // Last resort on the front page and posts index only: the site // tagline. Singles without excerpts stay undescribed rather than // repeating one tagline across every URL. if ( 'home' === $ctx->queriedType() && function_exists( 'get_bloginfo' ) ) { $tagline = trim( (string) get_bloginfo( 'description' ) ); if ( '' !== $tagline ) { return $tagline; } } return ''; } /** * Merge RankKernel robots directives into core's wp_robots array. * * Runs on the wp_robots filter so core emits the single robots tag for the * page. Directives merge most restrictive wins, so a noindex from either * side survives and any max budget keeps the tighter of the two values. * * @param array $robots Directives from core and other plugins. * @return array Merged directives. */ public function filterRobots( array $robots ): array { $ctx = $this->getContext(); // Feeds and previews render no RankKernel head output, core stays untouched. if ( in_array( $ctx->queriedType(), [ 'feed', 'preview' ], true ) ) { return $robots; } return $this->mergeRobots( $robots, $this->robotsDirectives( $ctx, $ctx->meta() ) ); } /** * Whether the queried object is an attachment page. * * An attachment page carries no text of its own, it is a wrapper around the * media file, so indexing it competes with the post the file belongs to. * PostsProvider already excludes attachments from the sitemaps, so this * governs the head directives only and does not double handle them. * * @param Context $ctx Context. * @return bool The result. */ private static function isAttachmentPage( Context $ctx ): bool { $id = $ctx->queriedId(); if ( $id <= 0 || ! function_exists( 'get_post_type' ) ) { return false; } return 'attachment' === get_post_type( $id ); } /** * Whether the queried post requires a password. * * @param Context $ctx Context. * @return bool The result. */ private static function isPasswordProtected( Context $ctx ): bool { $id = $ctx->queriedId(); if ( $id <= 0 || ! function_exists( 'post_password_required' ) ) { return false; } return (bool) post_password_required( $id ); } /** * Translate payload robots settings into wp_robots directive keys. * * @param Context $ctx Context. * @param array $meta Meta payload. * @return array Directive map. */ private function robotsDirectives( Context $ctx, array $meta ): array { $robots = $meta['robots'] ?? MetaPayload::defaults()['robots']; if ( ! is_array( $robots ) ) { $robots = MetaPayload::defaults()['robots']; } // Noindex rules: search, 404 and attachment pages are noindex, follow. // Password-protected posts are noindex, follow: render() emits no // tags for them, but core still prints the wp_robots tag from // filterRobots(), so the directive must carry the noindex itself. if ( in_array( $ctx->queriedType(), [ 'search', '404' ], true ) || self::isAttachmentPage( $ctx ) || self::isPasswordProtected( $ctx ) ) { $robots['index'] = false; $robots['follow'] = true; } $directives = []; if ( empty( $robots['index'] ) ) { $directives['noindex'] = true; } if ( empty( $robots['follow'] ) ) { $directives['nofollow'] = true; } foreach ( [ 'noarchive', 'noimageindex', 'nosnippet' ] as $flag ) { if ( ! empty( $robots[ $flag ] ) ) { $directives[ $flag ] = true; } } if ( isset( $robots['max_snippet'] ) && null !== $robots['max_snippet'] && '' !== $robots['max_snippet'] ) { $directives['max-snippet'] = (int) $robots['max_snippet']; } if ( isset( $robots['max_image_preview'] ) && null !== $robots['max_image_preview'] && '' !== $robots['max_image_preview'] ) { $directives['max-image-preview'] = (string) $robots['max_image_preview']; } if ( isset( $robots['max_video_preview'] ) && null !== $robots['max_video_preview'] && '' !== $robots['max_video_preview'] ) { $directives['max-video-preview'] = (int) $robots['max_video_preview']; } return $directives; } /** * Merge two directive maps, keeping the most restrictive value. * * @param array $base Directives from core and other plugins. * @param array $ours RankKernel directives. * @return array Merged directives. */ private function mergeRobots( array $base, array $ours ): array { $merged = $base; foreach ( [ 'noindex', 'nofollow', 'noarchive', 'noimageindex', 'nosnippet' ] as $flag ) { if ( ! empty( $ours[ $flag ] ) ) { $merged[ $flag ] = true; } } foreach ( [ 'max-snippet', 'max-video-preview' ] as $budget ) { if ( ! isset( $ours[ $budget ] ) ) { continue; } $merged[ $budget ] = isset( $merged[ $budget ] ) ? self::tighterBudget( (int) $merged[ $budget ], (int) $ours[ $budget ] ) : $ours[ $budget ]; } if ( isset( $ours['max-image-preview'] ) ) { $merged['max-image-preview'] = isset( $merged['max-image-preview'] ) ? self::tighterImagePreview( (string) $merged['max-image-preview'], (string) $ours['max-image-preview'] ) : $ours['max-image-preview']; } return $merged; } /** * Tighter of two numeric snippet or video budgets. * * A negative value means no limit, so any non negative value is tighter. * * @param int $a First budget. * @param int $b Second budget. * @return int Tighter budget. */ private static function tighterBudget( int $a, int $b ): int { if ( $a < 0 ) { return $b; } if ( $b < 0 ) { return $a; } return min( $a, $b ); } /** * Tighter of two max-image-preview values. * * @param string $a First value. * @param string $b Second value. * @return string Tighter value. */ private static function tighterImagePreview( string $a, string $b ): string { $rank = [ 'none' => 0, 'standard' => 1, 'large' => 2, ]; return ( $rank[ $a ] ?? 2 ) <= ( $rank[ $b ] ?? 2 ) ? $a : $b; } /** * Resolve canonical URL (omitted on search/404). * * @param Context $ctx Context. * @param array $meta Meta. * @return string The result. */ private function resolveCanonical( Context $ctx, array $meta ): string { if ( in_array( $ctx->queriedType(), [ 'search', '404' ], true ) ) { return ''; } $canonical = isset( $meta['canonical'] ) ? trim( (string) $meta['canonical'] ) : ''; if ( '' !== $canonical ) { return $canonical; } return $ctx->permalink(); } /** * Render OG tags. * * @param Context $ctx Context. * @param array $meta Meta. * @param string $description Resolved description for fallback. */ private function renderOgTags( Context $ctx, array $meta, string $description ): void { $og = $meta['og'] ?? []; if ( ! is_array( $og ) ) { $og = []; } // og:title. $ogTitle = isset( $og['title'] ) ? trim( (string) $og['title'] ) : ''; if ( '' === $ogTitle ) { $ogTitle = $this->getResolvedTitle( $ctx ); } if ( '' !== $ogTitle ) { echo '' . "\n"; } // og:description. $ogDesc = isset( $og['description'] ) ? trim( (string) $og['description'] ) : ''; if ( '' === $ogDesc ) { $ogDesc = $description; } if ( '' !== $ogDesc ) { echo '' . "\n"; } // og:url. if ( ! in_array( $ctx->queriedType(), [ 'search', '404' ], true ) ) { $ogUrl = $ctx->permalink(); if ( '' !== $ogUrl ) { echo '' . "\n"; } } // og:type. $ogType = isset( $og['type'] ) ? trim( (string) $og['type'] ) : ''; if ( '' === $ogType ) { if ( $ctx->isSingular() ) { $ogType = 'article'; } elseif ( 'home' === $ctx->queriedType() ) { $ogType = 'website'; } else { $ogType = 'website'; } } if ( '' !== $ogType ) { echo '' . "\n"; } // og:image (+ width/height only when emitted URL came from that attachment). $ogImage = $ctx->ogImage(); if ( '' !== $ogImage ) { echo '' . "\n"; $ogImageAlt = $ctx->ogImageAlt(); if ( '' !== $ogImageAlt ) { echo '' . "\n"; } $attachmentId = $ctx->ogImageAttachmentId(); if ( $attachmentId > 0 && function_exists( 'wp_get_attachment_image_src' ) ) { $src = wp_get_attachment_image_src( $attachmentId, 'large' ); if ( is_array( $src ) ) { echo '' . "\n"; echo '' . "\n"; } } } // og:site_name. $siteName = $ctx->siteName(); if ( '' !== $siteName ) { echo '' . "\n"; } // og:locale. $locale = function_exists( 'get_locale' ) ? (string) get_locale() : ''; if ( '' !== $locale ) { echo '' . "\n"; } if ( $ctx->isSingular() ) { $postId = $ctx->queriedId(); if ( $postId > 0 ) { if ( function_exists( 'get_the_date' ) ) { $published = get_the_date( 'c', $postId ); if ( is_string( $published ) && '' !== trim( $published ) ) { echo '' . "\n"; } } if ( function_exists( 'get_the_modified_date' ) ) { $modified = get_the_modified_date( 'c', $postId ); if ( is_string( $modified ) && '' !== trim( $modified ) ) { echo '' . "\n"; } } if ( function_exists( 'get_post_field' ) && function_exists( 'get_author_posts_url' ) ) { $authorId = get_post_field( 'post_author', $postId ); if ( is_numeric( $authorId ) && (int) $authorId > 0 ) { $authorUrl = get_author_posts_url( (int) $authorId ); if ( is_string( $authorUrl ) && '' !== trim( $authorUrl ) ) { echo '' . "\n"; } } } } } } /** * Render Twitter tags (fallback chain mirrors OG). * * @param Context $ctx Context. * @param array $meta Meta. */ private function renderTwitterTags( Context $ctx, array $meta ): void { $twitter = $meta['twitter'] ?? []; $og = $meta['og'] ?? []; if ( ! is_array( $twitter ) ) { $twitter = []; } if ( ! is_array( $og ) ) { $og = []; } // twitter:card (payload -> default summary_large_image). $card = isset( $twitter['card'] ) ? trim( (string) $twitter['card'] ) : ''; if ( '' === $card ) { $card = 'summary_large_image'; } echo '' . "\n"; // twitter:title fallback: payload twitter.title -> og.title -> resolved title. $twTitle = isset( $twitter['title'] ) ? trim( (string) $twitter['title'] ) : ''; if ( '' === $twTitle ) { $twTitle = isset( $og['title'] ) ? trim( (string) $og['title'] ) : ''; if ( '' === $twTitle ) { $twTitle = $this->getResolvedTitle( $ctx ); } } if ( '' !== $twTitle ) { echo '' . "\n"; } // twitter:description fallback: twitter.description -> og.description -> resolved description. $twDesc = isset( $twitter['description'] ) ? trim( (string) $twitter['description'] ) : ''; if ( '' === $twDesc ) { $twDesc = isset( $og['description'] ) ? trim( (string) $og['description'] ) : ''; if ( '' === $twDesc ) { $twDesc = $this->resolveDescription( $ctx, $meta ); } } if ( '' !== $twDesc ) { echo '' . "\n"; } // twitter:image fallback: twitter.image -> twitter.image_id -> og.image chain. $twImage = isset( $twitter['image'] ) ? trim( (string) $twitter['image'] ) : ''; if ( '' === $twImage && isset( $twitter['image_id'] ) && (int) $twitter['image_id'] > 0 && function_exists( 'wp_get_attachment_image_url' ) ) { $url = wp_get_attachment_image_url( (int) $twitter['image_id'], 'large' ); if ( is_string( $url ) && '' !== $url ) { $twImage = $url; } } if ( '' === $twImage ) { $twImage = $ctx->ogImage(); } if ( '' !== $twImage ) { echo '' . "\n"; } $siteHandle = MetaPayload::sanitizeTwitterHandle( $this->settings->get( 'twitter_site', '' ) ); if ( '' !== $siteHandle ) { echo '' . "\n"; } if ( $ctx->isSingular() ) { $creatorHandle = ''; $postId = $ctx->queriedId(); if ( function_exists( 'get_post_field' ) && function_exists( 'get_user_meta' ) ) { $authorId = get_post_field( 'post_author', $postId ); if ( is_numeric( $authorId ) && (int) $authorId > 0 ) { $creatorHandle = MetaPayload::sanitizeTwitterHandle( get_user_meta( (int) $authorId, 'rankkernel_twitter_handle', true ) ); } } if ( '' === $creatorHandle ) { $creatorHandle = $siteHandle; } if ( '' !== $creatorHandle ) { echo '' . "\n"; } } } /** * Render webmaster verification tags from settings. */ private function renderWebmasterTags(): void { $map = [ 'google' => 'google-site-verification', 'bing' => 'msvalidate.01', 'yandex' => 'yandex-verification', 'baidu' => 'baidu-site-verification', 'pinterest' => 'p:domain_verify', ]; foreach ( $map as $key => $metaName ) { $val = trim( (string) $this->settings->get( 'webmaster_' . $key, '' ) ); if ( '' !== $val ) { echo '' . "\n"; } } } }