PluginProbe
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO / 2.12.0
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO v2.12.0
2.12.0 2.11.0 2.10.0 2.9.0 2.8.0 2.7.0 2.6.0 2.5.0 2.4.0 2.3.0 2.2.0 2.1.1 2.1.0 2.0.2 2.0.1 2.0.0 1.32.0 1.31.0 1.30.0 1.29.0 1.28.0 1.27.0 1.26.0 1.25.0 trunk All 53 releases
← All changes | includes/frontend/class-seo-manager.php +1710 -151 1.26.0 → 2.12.0 View file →
@@ -41,8 +41,16 @@
41 41 */
42 42 private array $current_metadata = [];
43 43
44 44 /**
45 + * Term ID of the archive being rendered, when the request is a term archive.
46 + *
47 + * @since 2.0.1
48 + * @var int|null
49 + */
50 + private ?int $current_term_id = null;
51 +
52 + /**
45 53 * Site Identity Manager instance
46 54 *
47 55 * @var \ThinkRank\SEO\Site_Identity_Manager|null
48 56 */
@@ -48,8 +56,29 @@
48 56 */
49 57 private ?\ThinkRank\SEO\Site_Identity_Manager $site_identity_manager = null;
50 58
51 59 /**
60 + * Resolved icon URLs, keyed by "<md5 of configured URL>:<size>".
61 + *
62 + * wp_site_icon() renders four tags per page and each one resolves the same
63 + * setting, so without this the lookup is four rounds of
64 + * attachment_url_to_postid() — an uncached postmeta query apiece — for one
65 + * answer. Loaded from, and persisted to, a transient: this filter runs in
66 + * wp_head on every FRONT-END request, and the mapping only changes when the
67 + * icon setting does.
68 + *
69 + * @var array<string, string>|null Null until loaded.
70 + */
71 + private ?array $icon_urls = null;
72 +
73 + /**
74 + * Whether $icon_urls gained an entry that is not in the transient yet.
75 + *
76 + * @var bool
77 + */
78 + private bool $icon_urls_dirty = false;
79 +
80 + /**
52 81 * Social Meta Manager instance
53 82 *
54 83 * @var \ThinkRank\SEO\Social_Meta_Manager|null
55 84 */
@@ -83,8 +112,16 @@
83 112 */
84 113 private ?\ThinkRank\SEO\Image_SEO_Manager $image_seo_manager = null;
85 114
86 115 /**
116 + * External Links Manager instance
117 + *
118 + * @since 2.5.0
119 + * @var \ThinkRank\SEO\External_Links_Manager|null
120 + */
121 + private ?\ThinkRank\SEO\External_Links_Manager $external_links_manager = null;
122 +
123 + /**
87 124 * Current page context
88 125 *
89 126 * @var string
90 127 */
@@ -90,8 +127,39 @@
90 127 */
91 128 private string $current_context = 'site';
92 129
93 130 /**
131 + * Whether the opening "Search Engine Optimization by ThinkRank" comment has
132 + * already been printed for this request.
133 + *
134 + * Shared across the request rather than kept as a local `static` inside the
135 + * emitter, because the closing comment is printed from a different method
136 + * (and the opening one can also come from Author_Archives_Manager). Without
137 + * that, output_closing_comment() decided on its own always-false local
138 + * static and emitted an orphan `<!-- /ThinkRank SEO -->` on every page whose
139 + * meta description was empty.
140 + *
141 + * @since 2.0.1
142 + * @var bool
143 + */
144 + private static bool $opening_comment_output = false;
145 +
146 + /**
147 + * Memoised "should core's sitemap be disabled" flag. Null until resolved.
148 + *
149 + * @var bool|null
150 + */
151 + private ?bool $thinkrank_sitemap_enabled = null;
152 +
153 + /**
154 + * Memoised public URL of the sitemap ThinkRank publishes. Empty until
155 + * should_disable_core_sitemap() has resolved, and while it resolves false.
156 + *
157 + * @var string
158 + */
159 + private string $thinkrank_sitemap_url = '';
160 +
161 + /**
94 162 * Initialize SEO manager
95 163 *
96 164 * @return void
97 165 */
@@ -107,17 +175,22 @@
107 175
108 176 // Initialize Global SEO Schema Output
109 177 $this->initialize_global_seo_schema();
110 178
111 - // Initialize Google Analytics Tracking Manager
112 - $this->initialize_google_analytics_tracking();
113 -
114 179 // Initialize Image SEO Manager
115 180 $this->initialize_image_seo_manager();
116 181
182 + // Initialize External Links Manager (rel=nofollow / target=_blank)
183 + $this->initialize_external_links_manager();
184 +
117 185 // Initialize current post and context data first
118 186 add_action('wp', [$this, 'initialize_current_context']);
119 187
188 + // ...then let it be corrected if the request turns into a 404 later.
189 + // Late, so every set_404() on this hook has already run; still well
190 + // before wp_head, which the template fires.
191 + add_action('template_redirect', [$this, 'recheck_404_context'], 999);
192 +
120 193 // Use HIGH PRIORITY hooks to override other SEO plugins
121 194 // Priority 1-5 ensures ThinkRank runs before other SEO plugins
122 195
123 196 // Override WordPress title with HIGH priority
@@ -148,11 +221,27 @@
148 221 // the page would emit two <link rel="canonical"> tags on singular views.
149 222 remove_action('wp_head', 'rel_canonical');
150 223 add_action('wp_head', [$this, 'output_canonical_url'], 6);
151 224
225 + // Silence the Bricks theme's own SEO + Open Graph output so a Bricks
226 + // site doesn't ship two of every tag. Bricks is a THEME, so it loads
227 + // after plugins: at this point BRICKS_VERSION is not yet defined and a
228 + // `defined()` guard here would always be false. Registering the filters
229 + // unconditionally is correct and free — the hooks only ever fire from
230 + // inside Bricks itself (#257). This mirrors the core rel_canonical and
231 + // wp_robots removals above: one producer per tag.
232 + add_filter('bricks/frontend/disable_seo', '__return_true');
233 + add_filter('bricks/frontend/disable_opengraph', '__return_true');
234 +
152 235 // Add Site Identity specific outputs
153 236 add_action('wp_head', [$this, 'output_site_schema_markup'], 7);
154 237 add_action('wp_head', [$this, 'output_breadcrumb_schema'], 8);
238 + // Late enough that Global_SEO_Schema_Output (priority 15) has registered.
239 + add_action('wp_head', [$this, 'output_schema_graph'], 20);
240 + // Tell the graph it has a renderer, so a body producer asking whether
241 + // its FAQ was absorbed can trigger collection itself when a block theme
242 + // renders the post content ahead of wp_head.
243 + Schema_Graph::instance()->schedule_render();
155 244
156 245 // Add closing comment (runs last)
157 246 add_action('wp_head', [$this, 'output_closing_comment'], 99);
158 247
@@ -169,8 +258,46 @@
169 258
170 259 // Add robots.txt filter hook
171 260 add_filter('robots_txt', [$this, 'filter_robots_txt'], 10, 2);
172 261
262 + // Serve /llms.txt from PHP when the request reaches WordPress. A
263 + // published llms.txt is a physical file, so the web server normally
264 + // answers it — with `text/plain` and no charset, which renders UTF-8
265 + // content as mojibake. This route (plus the .htaccess block written by
266 + // LLMs_Txt_Manager for the static file) guarantees an explicit UTF-8
267 + // charset. Priority 8 keeps it ahead of redirect_canonical().
268 + add_action('template_redirect', [$this, 'maybe_serve_llms_txt'], 8);
269 +
270 + // Serve the sitemap from PHP on sites whose web root cannot be written.
271 + // ThinkRank publishes sitemaps as real files, so where that is possible
272 + // the web server answers first and this never runs; where it is not,
273 + // this is the only thing that answers at all, and without it the
274 + // feature was simply unavailable (#752). Same priority 8, and for the
275 + // same reason: ahead of redirect_canonical().
276 + add_action('template_redirect', [$this, 'maybe_serve_sitemap'], 8);
277 +
278 + // Take WordPress core's own sitemap offline while ThinkRank's is active.
279 + // Two sitemap indexes on one site is a crawl conflict: core keeps
280 + // /wp-sitemap.xml served and injects its own "Sitemap:" line into
281 + // robots.txt (WP_Sitemaps::add_robots, priority 0). Until now that line
282 + // only disappeared as a side effect of filter_robots_txt() replacing the
283 + // whole filter output, which does not happen when robots.txt management
284 + // is off, when Site Identity is disabled, or when another SEO plugin
285 + // claims the filter first — and it never took /wp-sitemap.xml itself
286 + // offline, so crawlers could still find and follow the duplicate index.
287 + add_filter('wp_sitemaps_enabled', [$this, 'filter_wp_sitemaps_enabled']);
288 +
289 + // …and point the URLs core owned at our sitemap, rather than letting
290 + // them dead-end. Disabling core's sitemap does not unhook the two core
291 + // paths that route /sitemap.xml: WP_Rewrite::rewrite_rules() adds the
292 + // `sitemap\.xml` rule unconditionally, and redirect_canonical() 301s any
293 + // request carrying the `sitemap` query var to /wp-sitemap.xml without
294 + // consulting wp_sitemaps_enabled — which then 404s. Runs before both
295 + // redirect_canonical() and WP_Sitemaps::render_sitemaps() (priority 10),
296 + // and after a Pro redirect rule (priority 1) so a user-defined redirect
297 + // for these URLs still wins.
298 + add_action('template_redirect', [$this, 'redirect_core_sitemap_requests'], 9);
299 +
173 300 // Keep an existing physical robots.txt in step with WordPress's
174 301 // "Discourage search engines" toggle (blog_public). A physical file
175 302 // bypasses core's robots_txt filter, so flipping blog_public after the
176 303 // file was written would otherwise leave the previous crawl policy served
@@ -180,8 +307,17 @@
180 307 // Serve the Site Identity favicon through core's site-icon pipeline so
181 308 // wp_site_icon() outputs it on the front-end (and previews pick it up)
182 309 add_filter('get_site_icon_url', [$this, 'filter_site_icon_url'], 10, 2);
183 310
311 + // Rewrite outbound anchors (rel=nofollow / target=_blank). Runs at
312 + // the very end of the_content, after core's formatting AND after the
313 + // image filter above, so it sees the markup the visitor will get. The
314 + // stored post_content is never touched — turning the settings off
315 + // restores the author's markup exactly.
316 + add_filter('the_content', [$this, 'filter_external_links'], 100000);
317 + add_filter('the_excerpt', [$this, 'filter_external_links'], 100000);
318 + add_filter('widget_text_content', [$this, 'filter_external_links'], 100000);
319 +
184 320 // Process image SEO in content
185 321 add_filter('the_content', [$this, 'filter_content_images'], 99999);
186 322 add_filter('post_thumbnail_html', [$this, 'filter_content_images'], 11, 2);
187 323 add_filter('woocommerce_single_product_image_thumbnail_html', [$this, 'filter_content_images'], 11);
@@ -241,39 +377,73 @@
241 377 }
242 378
243 379 // Initialize Global SEO Schema Output and store reference
244 380 $this->global_seo_schema = new Global_SEO_Schema_Output();
381 + // Let schema reuse the description this class already resolves, so the
382 + // JSON-LD and the meta/og/twitter tags cannot disagree about what the
383 + // page is (#766). Passed as a callback rather than a value: schema is
384 + // built during wp_head, by which point the request context this
385 + // resolution depends on is set, and it must not be captured earlier.
386 + $this->global_seo_schema->set_description_resolver(
387 + fn (): string => (string) $this->get_meta_description()
388 + );
245 389 $this->global_seo_schema->init();
246 390 }
247 391
248 392 /**
249 - * Initialize Google Analytics Tracking Manager
393 + * Initialize Image SEO Manager
250 394 *
251 395 * @return void
252 396 */
253 - private function initialize_google_analytics_tracking(): void {
254 - if (!class_exists('ThinkRank\\Frontend\\Google_Analytics_Tracking_Manager')) {
255 - require_once THINKRANK_PLUGIN_DIR . 'includes/frontend/class-google-analytics-tracking-manager.php';
397 + private function initialize_image_seo_manager(): void {
398 + if (!class_exists('ThinkRank\\SEO\\Image_SEO_Manager')) {
399 + require_once THINKRANK_PLUGIN_DIR . 'includes/seo/class-image-seo-manager.php';
256 400 }
257 401
258 - // Initialize Google Analytics Tracking Manager
259 - new \ThinkRank\Frontend\Google_Analytics_Tracking_Manager();
402 + $this->image_seo_manager = new \ThinkRank\SEO\Image_SEO_Manager();
260 403 }
261 404
262 405 /**
263 - * Initialize Image SEO Manager
406 + * Initialize External Links Manager
264 407 *
408 + * @since 2.5.0
265 409 * @return void
266 410 */
267 - private function initialize_image_seo_manager(): void {
268 - if (!class_exists('ThinkRank\\SEO\\Image_SEO_Manager')) {
269 - require_once THINKRANK_PLUGIN_DIR . 'includes/seo/class-image-seo-manager.php';
411 + private function initialize_external_links_manager(): void {
412 + if (!class_exists('ThinkRank\\SEO\\External_Links_Manager')) {
413 + require_once THINKRANK_PLUGIN_DIR . 'includes/seo/class-external-links-manager.php';
270 414 }
271 415
272 - $this->image_seo_manager = new \ThinkRank\SEO\Image_SEO_Manager();
416 + $this->external_links_manager = new \ThinkRank\SEO\External_Links_Manager();
273 417 }
274 418
275 419 /**
420 + * Filter rendered content to annotate external links
421 + *
422 + * @since 2.5.0
423 + * @param mixed $content Content to filter; passed through untouched when
424 + * it is not a string.
425 + * @return mixed Filtered content.
426 + */
427 + public function filter_external_links($content) {
428 + // No return type: a filter value another plugin hands through as null
429 + // or an object belongs to whoever set it, and coercing it to '' would
430 + // silently drop their content on the floor.
431 + if (!is_string($content) || $content === '' || !$this->external_links_manager) {
432 + return $content;
433 + }
434 +
435 + // Feeds carry the same markup to a reader we do not control; leave
436 + // them as authored rather than annotating for a context that has no
437 + // browser tab to open.
438 + if (is_feed()) {
439 + return $content;
440 + }
441 +
442 + return $this->external_links_manager->process_content($content);
443 + }
444 +
445 + /**
276 446 * Filter content to inject image SEO attributes
277 447 *
278 448 * @since 1.0.0
279 449 * @param string $content Content to filter
@@ -325,18 +495,74 @@
325 495 $this->current_metadata = $this->get_post_seo_metadata($post_id);
326 496 }
327 497 }
328 498
499 + // Term archives. Category, tag and custom-taxonomy pages store their SEO
500 + // title and description as term meta — written by the term UI, by the
501 + // abilities API and by the Yoast/RankMath/AIOSEO/SEOPress importer — but
502 + // nothing here ever read them, so the whole title/description cascade
503 + // fell through to the theme default and no description tag was printed
504 + // at all. Term robots was fixed for the same reason in 1.31.0 (#290);
505 + // this is the title and description half (#386).
506 + if (is_category() || is_tag() || is_tax()) {
507 + $queried = get_queried_object();
508 + if ($queried instanceof \WP_Term) {
509 + $this->current_term_id = $queried->term_id;
510 + $this->current_metadata = $this->get_term_seo_metadata($queried->term_id);
511 + }
512 + }
513 +
329 514 // Load site identity data
330 515 $this->load_site_identity_data();
331 516 }
332 517
333 518 /**
519 + * Drop the request's post identity once it has become a 404.
520 + *
521 + * `initialize_current_context()` runs on `wp`, but a request can be turned
522 + * into a 404 after that: `set_404()` on `template_redirect` is the ordinary
523 + * way to refuse a URL that did resolve to a real post, and both core and
524 + * plugins do it — ThinkRank Pro's Markdown for AI refuses an ineligible
525 + * `.md` URL that way. The snapshot still said `post`/`page` and still held
526 + * the post id and its metadata, so the error page shipped that post's meta
527 + * description, focus keywords and — where the social emitters got that far
528 + * — its og:description and twitter:description, all of which a request that
529 + * was a 404 from the start never prints (#655).
530 + *
531 + * Clearing the snapshot rather than special-casing each emitter is what
532 + * makes every consumer agree, including the ones that read
533 + * `$current_metadata` without ever asking what the context is.
534 + *
535 + * @since 2.3.1
536 + *
537 + * @return void
538 + */
539 + public function recheck_404_context(): void {
540 + if (!is_404() || '404' === $this->current_context) {
541 + return;
542 + }
543 +
544 + $this->current_context = '404';
545 + $this->current_post_id = null;
546 + $this->current_term_id = null;
547 + $this->current_metadata = [];
548 + }
549 +
550 + /**
334 551 * Detect current page context
335 552 *
336 553 * @return string Current context type
337 554 */
338 555 private function detect_current_context(): string {
556 + // 404 first: a not-found request matches none of the branches below and
557 + // used to fall through to 'site', which handed crawlers the homepage's
558 + // social identity for an error page. It gets its own context so the
559 + // social layer can skip it, matching get_non_singular_canonical_url(),
560 + // which already suppresses the canonical for 404 and search.
561 + if (is_404()) {
562 + return '404';
563 + }
564 +
339 565 if (is_home() || is_front_page()) {
340 566 return 'homepage';
341 567 } elseif (is_single()) {
342 568 return 'post';
@@ -392,8 +618,37 @@
392 618 ];
393 619 }
394 620
395 621 /**
622 + * Get SEO metadata for a term.
623 + *
624 + * Mirrors get_post_seo_metadata(): the stored values may carry variable
625 + * tags, so they are resolved against the term's own values. Focus keyword
626 + * and score have no term equivalent on the frontend and stay empty.
627 + *
628 + * @since 2.0.1
629 + *
630 + * @param int $term_id Term ID.
631 + * @return array SEO metadata.
632 + */
633 + private function get_term_seo_metadata(int $term_id): array {
634 + $title = get_term_meta($term_id, '_thinkrank_seo_title', true);
635 + $description = get_term_meta($term_id, '_thinkrank_meta_description', true);
636 +
637 + return [
638 + 'title' => $title
639 + ? \ThinkRank\SEO\Pattern_Resolver::resolve_term_value((string) $title, $term_id)
640 + : '',
641 + 'description' => $description
642 + ? \ThinkRank\SEO\Pattern_Resolver::resolve_term_value((string) $description, $term_id)
643 + : '',
644 + 'focus_keyword' => '',
645 + 'focus_keywords' => [],
646 + 'seo_score' => '',
647 + ];
648 + }
649 +
650 + /**
396 651 * Resolve the effective SEO title for the current request.
397 652 *
398 653 * Same priority chain as override_document_title() — post-specific
399 654 * ThinkRank metadata (resolved _thinkrank_seo_title) > Global SEO
@@ -418,17 +673,23 @@
418 673 * @param string $title Original title
419 674 * @return string Modified title
420 675 */
421 676 public function override_document_title($title): string {
677 + // A content type with metas switched off keeps whatever title the theme
678 + // and WordPress produce (#660).
679 + if (!$this->metas_enabled()) {
680 + return $title;
681 + }
682 +
422 683 // First priority: Post-specific ThinkRank metadata
423 684 if ($this->has_thinkrank_metadata() && !empty($this->current_metadata['title'])) {
424 - return $this->current_metadata['title'];
685 + return self::with_page_suffix($this->current_metadata['title']);
425 686 }
426 687
427 688 // Second priority: Global SEO templates, Third priority: Site Identity templates
428 689 $generated_title = $this->generate_context_title();
429 690 if ($generated_title) {
430 - return $generated_title;
691 + return self::with_page_suffix($generated_title);
431 692 }
432 693
433 694 return $title;
434 695 }
@@ -433,8 +694,117 @@
433 694 return $title;
434 695 }
435 696
436 697 /**
698 + * Append a page indicator to a title on page 2 and beyond.
699 + *
700 + * This filter short-circuits pre_get_document_title at priority 1, which
701 + * drops the " – Page 2" core would otherwise add — so every page of an
702 + * archive, and every part of a multi-page post, shared one <title> (#397).
703 + * The templates have no %page% token, so the suffix is added here rather
704 + * than asking every site to edit its title format.
705 + *
706 + * @since 2.0.1
707 + *
708 + * @param string $title Resolved title.
709 + * @return string Title with the page indicator, when there is one.
710 + */
711 + /**
712 + * The archive's subject, without the label WordPress prefixes it with.
713 + *
714 + * `get_the_archive_title()` returns "Month: September 2026", "Archives:
715 + * Recipes", "Category: Uncategorized" — the label is core's, aimed at an
716 + * archive heading on the page, and it reads badly in a browser tab, an
717 + * og:title or a search result. Category, tag and author contexts already
718 + * avoid it by using the raw name; the generic archive context did not, so
719 + * date, custom-post-type and custom-taxonomy archives carried it (#640).
720 + *
721 + * Removed through core's own `get_the_archive_title_prefix` filter rather
722 + * than by matching the prefix text, because that text is translated and
723 + * differs per archive type — a string comparison would work in English and
724 + * silently stop working everywhere else.
725 + *
726 + * A site that wants a prefix can put one in its title template, where it is
727 + * visible and editable, instead of inheriting one it cannot see.
728 + *
729 + * @since 2.7.0
730 + *
731 + * @return string Archive subject, with markup and the core prefix removed.
732 + */
733 + private static function archive_subject(): string {
734 + $drop_prefix = static function (): string {
735 + return '';
736 + };
737 +
738 + add_filter('get_the_archive_title_prefix', $drop_prefix, 99);
739 +
740 + $title = (string) get_the_archive_title();
741 +
742 + remove_filter('get_the_archive_title_prefix', $drop_prefix, 99);
743 +
744 + // The <span> core wraps the subject in survives the prefix filter.
745 + return trim(wp_strip_all_tags($title));
746 + }
747 +
748 + /**
749 + * Remove HTML from a title that is about to be emitted.
750 + *
751 + * A title carrying markup is broken twice over, in two different ways, and
752 + * both were reaching real pages: inside `<title>` the tags render literally,
753 + * because that element is RCDATA and never parses them; inside `og:title`
754 + * and `twitter:title` they are attribute-escaped, so the reader sees
755 + * `&lt;em&gt;` as visible text (#640).
756 + *
757 + * Applied at the point of emission rather than at each source, so it covers
758 + * every branch that can produce a title — post meta, Global SEO templates,
759 + * Site Identity templates — without each having to remember.
760 + *
761 + * Unconditional rather than a setting: there is no title for which markup is
762 + * the correct output. The filter is the escape hatch for anyone who
763 + * disagrees, and lets a site keep entities it deliberately encoded.
764 + *
765 + * @since 2.7.0
766 + *
767 + * @param string $title Title about to be emitted.
768 + * @return string Title with any markup removed.
769 + */
770 + public static function strip_title_tags(string $title): string {
771 + /**
772 + * Filter whether HTML is stripped from generated titles.
773 + *
774 + * @since 2.7.0
775 + *
776 + * @param bool $strip Whether to strip. Default true.
777 + * @param string $title The title being emitted.
778 + */
779 + if (!apply_filters('thinkrank_strip_title_tags', true, $title)) {
780 + return $title;
781 + }
782 +
783 + return trim(wp_strip_all_tags($title));
784 + }
785 +
786 + public static function with_page_suffix(string $title): string {
787 + $title = self::strip_title_tags($title);
788 +
789 + $page = self::current_page_number();
790 +
791 + if ($page <= 1 || '' === $title) {
792 + return $title;
793 + }
794 +
795 + $separator = class_exists('\ThinkRank\SEO\Site_Identity_Manager')
796 + ? \ThinkRank\SEO\Site_Identity_Manager::get_active_separator_symbol()
797 + : '|';
798 +
799 + return $title . ' ' . $separator . ' ' . sprintf(
800 + /* translators: %d: page number. */
801 + __('Page %d', 'thinkrank'),
802 + $page
803 + );
804 + }
805 +
806 + /**
437 807 * Override WordPress wp_title (HIGH PRIORITY)
438 808 * Priority: Post-specific metadata > Global SEO templates > Site Identity templates
439 809 *
440 810 * @param string $title Original title
@@ -441,18 +811,24 @@
441 811 * @param string $sep Title separator
442 812 * @return string Modified title
443 813 */
444 814 public function override_wp_title(string $title, string $sep = ''): string {
815 + if (!$this->metas_enabled()) {
816 + return $title;
817 + }
818 +
445 819 // First priority: Post-specific ThinkRank metadata
446 820 if ($this->has_thinkrank_metadata() && !empty($this->current_metadata['title'])) {
447 821 $site_name = get_bloginfo('name');
448 - return $this->current_metadata['title'] . ($sep ? " $sep " : ' | ') . $site_name;
822 + return self::with_page_suffix(
823 + $this->current_metadata['title'] . ($sep ? " $sep " : ' | ') . $site_name
824 + );
449 825 }
450 826
451 827 // Second priority: Global SEO templates, Third priority: Site Identity templates
452 828 $generated_title = $this->generate_context_title();
453 829 if ($generated_title) {
454 - return $generated_title;
830 + return self::with_page_suffix($generated_title);
455 831 }
456 832
457 833 return $title;
458 834 }
@@ -457,28 +833,57 @@
457 833 return $title;
458 834 }
459 835
460 836 /**
837 + * Whether ThinkRank owns the title and meta description for this request.
838 + *
839 + * Metas are on site-wide by default; the per-content-type matrix can switch
840 + * them off for one content type, in which case ThinkRank stops overriding
841 + * the document title and prints no meta description (#660).
842 + *
843 + * @since 2.5.0
844 + * @return bool
845 + */
846 + private function metas_enabled(): bool {
847 + return \ThinkRank\SEO\Content_Type_Settings::is_enabled_for_current(
848 + \ThinkRank\SEO\Content_Type_Settings::FEATURE_META,
849 + true
850 + );
851 + }
852 +
853 + /**
461 854 * Output meta description (HIGH PRIORITY)
462 855 * Priority: Post-specific metadata > Global SEO templates > Site Identity templates > WordPress defaults
463 856 *
857 + * Author archives are skipped entirely: Author_Archives_Manager owns that
858 + * context and prints its own template-based description on wp_head at
859 + * priority 5. get_archive_meta_description() already declines to build one
860 + * there, but the fallback chain used to continue into the Site Identity
861 + * default, so the page ended up with two <meta name="description"> tags.
862 + *
464 863 * @return void
465 864 */
466 865 public function output_meta_description(): void {
866 + if (is_author()) {
867 + return;
868 + }
869 +
870 + if (!$this->metas_enabled()) {
871 + return;
872 + }
873 +
467 874 $description = $this->get_meta_description();
468 875
469 876 if ($description) {
470 877 // Output main ThinkRank SEO header comment (only once)
471 - static $header_output = false;
472 - if (!$header_output) {
473 - echo "<!-- Search Engine Optimization by ThinkRank - https://thinkrank.ai/ -->\n";
474 - $header_output = true;
475 - }
878 + self::note_opening_comment();
476 879
477 880 // Ensure description is within optimal length (150-160 characters)
478 - if (strlen($description) > 160) {
479 - $description = wp_trim_words($description, 25, '...');
480 - }
881 + // Measure and cut in CHARACTERS. strlen() counts bytes, so a Thai or
882 + // CJK description tripped this limit at a third of its length, and
883 + // wp_trim_words() then cut by a unit the locale chooses — 25 words in
884 + // English, 25 characters in Thai (#687).
885 + $description = \ThinkRank\Core\Seo_Text::trim_to_length($description);
481 886
482 887 echo "<!-- ThinkRank SEO Meta Description -->\n";
483 888 echo '<meta name="description" content="' . esc_attr($description) . '" />' . "\n";
484 889 echo "<!-- /ThinkRank SEO Meta Description -->\n";
@@ -519,13 +924,41 @@
519 924
520 925 // Output generator meta tag
521 926 echo '<meta name="generator" content="ThinkRank ' . esc_attr(THINKRANK_VERSION) . '" />' . "\n";
522 927
523 - // Output viewport meta tag if not already present
524 - if (!has_action('wp_head', 'wp_site_icon') || !wp_is_mobile()) {
525 - echo '<meta name="viewport" content="width=device-width, initial-scale=1.0" />' . "\n";
928 + // No viewport tag here. The viewport is the theme's responsibility and
929 + // every modern theme ships one, so emitting our own only ever produced a
930 + // second <meta name="viewport"> in the document. The old guard could not
931 + // prevent that either: has_action() returns the registered priority
932 + // (truthy), so its first operand was always false, and !wp_is_mobile() is
933 + // true for every desktop request.
934 + echo "<!-- /ThinkRank SEO Meta Tags -->\n";
935 + }
936 +
937 + /**
938 + * Build the basic robots directive list from a set of robots flags.
939 + *
940 + * Shared by the search/404 branch of get_robots_meta_content() so those
941 + * pages resolve their directives through the same rules as everything else
942 + * rather than a hardcoded literal.
943 + *
944 + * @since 2.5.0
945 + * @param array $settings Robots flags (index/noindex/nofollow/...).
946 + * @return string[] Directives.
947 + */
948 + private static function build_robots_directives(array $settings): array {
949 + $robots = [];
950 +
951 + $robots[] = !empty($settings['noindex']) ? 'noindex' : 'index';
952 + $robots[] = !empty($settings['nofollow']) ? 'nofollow' : 'follow';
953 +
954 + foreach (['noarchive', 'noimageindex', 'nosnippet'] as $directive) {
955 + if (!empty($settings[$directive])) {
956 + $robots[] = $directive;
957 + }
526 958 }
527 - echo "<!-- /ThinkRank SEO Meta Tags -->\n";
959 +
960 + return $robots;
528 961 }
529 962
530 963 /**
531 964 * Get robots meta content based on context and settings
@@ -534,13 +967,22 @@
534 967 */
535 968 private function get_robots_meta_content(): string {
536 969 $robots = [];
537 970
538 - // 404 and search results must never be indexed, regardless of the
539 - // configured global/post-type directives. Links are still followed so
540 - // crawlers can discover the rest of the site.
971 + // 404 and search results are noindex/follow by default — the behaviour
972 + // that used to be hardcoded here. It is now settings-driven (#660): the
973 + // Content Type Matrix can give either its own robots directives, and an
974 + // install that never touched them resolves to exactly the old pair.
541 975 if (is_404() || is_search()) {
542 - $robots = apply_filters('thinkrank_robots_meta', ['noindex', 'follow']);
976 + $entity = is_404()
977 + ? \ThinkRank\SEO\Content_Type_Settings::ENTITY_404
978 + : \ThinkRank\SEO\Content_Type_Settings::ENTITY_SEARCH;
979 +
980 + $robots = self::build_robots_directives(
981 + \ThinkRank\SEO\Content_Type_Settings::resolve_robots_meta($entity)
982 + );
983 +
984 + $robots = apply_filters('thinkrank_robots_meta', $robots);
543 985 return implode(', ', array_unique($robots));
544 986 }
545 987
546 988 // 1. Get global robot meta settings (Base)
@@ -569,8 +1011,24 @@
569 1011 $current_settings = array_merge($current_settings, $global_seo_settings[$post_type]['robots_meta']);
570 1012 }
571 1013 }
572 1014
1015 + // 2b. Apply the per-entity directives for the non-singular content
1016 + // types the matrix covers — taxonomy archives plus author and date
1017 + // archives. Terms keep their own per-term override, applied further
1018 + // down so it still wins over the taxonomy-wide value (#660).
1019 + if (!is_singular()) {
1020 + $entity_key = \ThinkRank\SEO\Content_Type_Settings::current_entity_key();
1021 +
1022 + if ($entity_key !== null) {
1023 + $entity_settings = \ThinkRank\SEO\Content_Type_Settings::get_entity_settings($entity_key);
1024 +
1025 + if (!empty($entity_settings['robots_meta_enabled']) && is_array($entity_settings['robots_meta'] ?? null)) {
1026 + $current_settings = array_merge($current_settings, $entity_settings['robots_meta']);
1027 + }
1028 + }
1029 + }
1030 +
573 1031 // Determine Index/Noindex based on merged settings
574 1032 // Priority: if noindex is true, it overrides index
575 1033 if (!empty($current_settings['noindex'])) {
576 1034 $robots[] = 'noindex';
@@ -634,12 +1092,30 @@
634 1092 $robots = $this->apply_post_robots_override(get_the_ID(), $robots, $current_settings);
635 1093 }
636 1094
637 1095 // Check for archive pages (search is handled by the early return above)
638 - if (is_archive()) {
1096 + //
1097 + // is_home() is deliberately included: the blog listing is not an
1098 + // is_archive(), so page 2 of a term archive was noindex while page 2 of
1099 + // the blog listing was index — the same kind of page, treated two
1100 + // different ways, on the same site (#397).
1101 + if (is_archive() || is_home()) {
639 1102 // Allow indexing of category/tag archives but be more conservative
640 1103 if (is_paged()) {
641 - $robots = ['noindex', 'follow'];
1104 + /**
1105 + * Filter whether a paginated archive is set noindex.
1106 + *
1107 + * Rank Math and Yoast now index paginated archives with a
1108 + * self-referential canonical by default, so a site that wants
1109 + * that can have it without patching.
1110 + *
1111 + * @since 2.0.1
1112 + *
1113 + * @param bool $noindex Whether to noindex this paginated page.
1114 + */
1115 + if (apply_filters('thinkrank_noindex_paged_archives', true)) {
1116 + $robots = ['noindex', 'follow'];
1117 + }
642 1118 }
643 1119
644 1120 // Honor the global date-archive noindex toggle (written by the
645 1121 // Rank Math/Yoast settings importer). Author archives are handled
@@ -648,8 +1124,27 @@
648 1124 $robots = ['noindex', 'follow'];
649 1125 }
650 1126 }
651 1127
1128 + // 4. Term meta override for taxonomy archives (Overrides everything).
1129 + //
1130 + // Terms had no branch here at all — not a wrong key or a skipped
1131 + // conditional, the lookup simply did not exist — so a category, tag or
1132 + // custom-taxonomy archive saved with noindex still rendered the global
1133 + // default. The stored value read back correctly through the abilities
1134 + // API, which made the setting look applied when it never reached output.
1135 + //
1136 + // Deliberately placed *after* the archive block so it is a real
1137 + // override, matching how a per-post override is final for singular
1138 + // views. Running it earlier would let is_paged() overwrite a term's
1139 + // explicit directives on page 2 of its own archive.
1140 + if (is_category() || is_tag() || is_tax()) {
1141 + $queried = get_queried_object();
1142 + if ($queried instanceof \WP_Term) {
1143 + $robots = $this->apply_term_robots_override($queried->term_id, $robots, $current_settings);
1144 + }
1145 + }
1146 +
652 1147 // Apply filters for customization
653 1148 $robots = apply_filters('thinkrank_robots_meta', $robots);
654 1149
655 1150 // Remove duplicates and implode
@@ -668,20 +1163,69 @@
668 1163 * @param array $current_settings Effective robots flags (global + post type)
669 1164 * @return array Updated robots directive list
670 1165 */
671 1166 private function apply_post_robots_override(int $post_id, array $robots, array $current_settings): array {
672 - if (!(bool) get_post_meta($post_id, '_thinkrank_robots_meta_enabled', true)) {
1167 + return $this->apply_meta_robots_override(
1168 + (bool) get_post_meta($post_id, '_thinkrank_robots_meta_enabled', true),
1169 + (string) get_post_meta($post_id, '_thinkrank_robots_meta', true),
1170 + (string) get_post_meta($post_id, '_thinkrank_advanced_robots_meta', true),
1171 + $robots,
1172 + $current_settings
1173 + );
1174 + }
1175 +
1176 + /**
1177 + * Apply per-term robots overrides on top of the cascaded directives.
1178 + *
1179 + * The term-meta twin of apply_post_robots_override(). Terms store the same
1180 + * three keys with the same shapes — written by the update-term-seo ability
1181 + * and by the Rank Math / Yoast / AIOSEO / SEOPress importer — so the two
1182 + * paths share one engine rather than a second copy that can drift.
1183 + *
1184 + * @since 1.31.0
1185 + *
1186 + * @param int $term_id Term being rendered
1187 + * @param array $robots Directives accumulated so far
1188 + * @param array $current_settings Effective robots flags (global + post type)
1189 + * @return array Updated robots directive list
1190 + */
1191 + private function apply_term_robots_override(int $term_id, array $robots, array $current_settings): array {
1192 + return $this->apply_meta_robots_override(
1193 + (bool) get_term_meta($term_id, '_thinkrank_robots_meta_enabled', true),
1194 + (string) get_term_meta($term_id, '_thinkrank_robots_meta', true),
1195 + (string) get_term_meta($term_id, '_thinkrank_advanced_robots_meta', true),
1196 + $robots,
1197 + $current_settings
1198 + );
1199 + }
1200 +
1201 + /**
1202 + * Rebuild the robots directives from a stored override, whatever holds it.
1203 + *
1204 + * Kept free of get_post_meta()/get_term_meta() so posts and terms cannot
1205 + * diverge: term support was missing entirely because the only override
1206 + * logic lived behind a post-meta read.
1207 + *
1208 + * @since 1.31.0
1209 + *
1210 + * @param bool $enabled Whether the override is switched on
1211 + * @param string $raw_robots JSON robots flags
1212 + * @param string $raw_advanced JSON advanced directives
1213 + * @param array $robots Directives accumulated so far
1214 + * @param array $current_settings Effective robots flags (global + post type)
1215 + * @return array Updated robots directive list
1216 + */
1217 + private function apply_meta_robots_override(bool $enabled, string $raw_robots, string $raw_advanced, array $robots, array $current_settings): array {
1218 + if (!$enabled) {
673 1219 return $robots;
674 1220 }
675 1221
676 - $raw_robots = get_post_meta($post_id, '_thinkrank_robots_meta', true);
677 - $post_robots = is_string($raw_robots) && $raw_robots !== '' ? json_decode($raw_robots, true) : null;
1222 + $post_robots = $raw_robots !== '' ? json_decode($raw_robots, true) : null;
678 1223 if (!is_array($post_robots)) {
679 1224 return $robots;
680 1225 }
681 1226
682 - $raw_advanced = get_post_meta($post_id, '_thinkrank_advanced_robots_meta', true);
683 - $post_advanced = is_string($raw_advanced) && $raw_advanced !== '' ? json_decode($raw_advanced, true) : null;
1227 + $post_advanced = $raw_advanced !== '' ? json_decode($raw_advanced, true) : null;
684 1228
685 1229 $effective = array_merge($current_settings, array_intersect_key($post_robots, array_flip([
686 1230 'index', 'noindex', 'nofollow', 'noarchive', 'noimageindex', 'nosnippet',
687 1231 ])));
@@ -851,9 +1395,9 @@
851 1395 *
852 1396 * @param array $og_tags Open Graph tags array
853 1397 * @return void
854 1398 */
855 - private function output_social_og_tags(array $og_tags): void {
1399 + private function output_social_og_tags(array $og_tags, array $extra_images = []): void {
856 1400 // Honor the thinkrank_og_type filter here too — this "Enhanced" path is
857 1401 // the active OG emitter, so add-ons (e.g. Pro's WooCommerce module which
858 1402 // sets 'product' on product pages) must be applied to it, not only to
859 1403 // output_open_graph_tags().
@@ -884,8 +1428,9 @@
884 1428
885 1429 // Output tags in optimal order
886 1430 foreach ($og_order as $property) {
887 1431 if (!empty($og_tags[$property])) {
1432 + // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- esc_meta_value() applies esc_url()/esc_attr(); the sniff cannot follow a method call.
888 1433 echo '<meta property="' . esc_attr($property) . '" content="' . $this->esc_meta_value($property, $og_tags[$property]) . '" />' . "\n";
889 1434 }
890 1435 }
891 1436
@@ -891,16 +1436,67 @@
891 1436
892 1437 // Output any remaining tags not in the order list
893 1438 foreach ($og_tags as $property => $content) {
894 1439 if (!empty($content) && !in_array($property, $og_order, true)) {
1440 + // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- esc_meta_value() applies esc_url()/esc_attr(); the sniff cannot follow a method call.
895 1441 echo '<meta property="' . esc_attr($property) . '" content="' . $this->esc_meta_value($property, $content) . '" />' . "\n";
896 1442 }
897 1443 }
898 1444
1445 + // Alternatives, after the primary and everything belonging to it.
1446 + // Order is the whole point: a consumer reads og:image tags in document
1447 + // order and treats the first as primary, and a structured property
1448 + // attaches to the most recently declared image — so each alternative's
1449 + // companions have to follow its own URL, not be grouped at the end.
1450 + self::output_extra_og_images($extra_images);
1451 +
899 1452 echo "<!-- /ThinkRank SEO Open Graph Tags -->\n";
900 1453 }
901 1454
902 1455 /**
1456 + * Emit the secondary og:image tags a page offers.
1457 + *
1458 + * Shared by the enhanced and basic emitters so both describe an
1459 + * alternative image the same way (#636).
1460 + *
1461 + * @since 2.7.0
1462 + *
1463 + * @param array $images Each with url, and width/height/type/alt where known.
1464 + * @return void
1465 + */
1466 + private static function output_extra_og_images(array $images): void {
1467 + foreach ($images as $image) {
1468 + $url = isset($image['url']) ? (string) $image['url'] : '';
1469 +
1470 + if ('' === $url) {
1471 + continue;
1472 + }
1473 +
1474 + echo '<meta property="og:image" content="' . esc_url($url) . '" />' . "\n";
1475 +
1476 + if (strpos($url, 'https://') === 0) {
1477 + echo '<meta property="og:image:secure_url" content="' . esc_url($url) . '" />' . "\n";
1478 + }
1479 +
1480 + // Only what is actually known: a dimension guessed for a remote
1481 + // image is a number a consumer lays a card out with before it has
1482 + // fetched the file.
1483 + if (!empty($image['width']) && !empty($image['height'])) {
1484 + echo '<meta property="og:image:width" content="' . esc_attr((string) $image['width']) . '" />' . "\n";
1485 + echo '<meta property="og:image:height" content="' . esc_attr((string) $image['height']) . '" />' . "\n";
1486 + }
1487 +
1488 + if (!empty($image['type'])) {
1489 + echo '<meta property="og:image:type" content="' . esc_attr((string) $image['type']) . '" />' . "\n";
1490 + }
1491 +
1492 + if (!empty($image['alt'])) {
1493 + echo '<meta property="og:image:alt" content="' . esc_attr((string) $image['alt']) . '" />' . "\n";
1494 + }
1495 + }
1496 + }
1497 +
1498 + /**
903 1499 * Output social media Twitter Card tags from Social Meta Manager
904 1500 *
905 1501 * @param array $twitter_tags Twitter Card tags array
906 1502 * @return void
@@ -921,8 +1517,9 @@
921 1517
922 1518 // Output tags in optimal order
923 1519 foreach ($twitter_order as $name) {
924 1520 if (!empty($twitter_tags[$name])) {
1521 + // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- esc_meta_value() applies esc_url()/esc_attr(); the sniff cannot follow a method call.
925 1522 echo '<meta name="' . esc_attr($name) . '" content="' . $this->esc_meta_value($name, $twitter_tags[$name]) . '" />' . "\n";
926 1523 }
927 1524 }
928 1525
@@ -928,8 +1525,9 @@
928 1525
929 1526 // Output any remaining tags not in the order list
930 1527 foreach ($twitter_tags as $name => $content) {
931 1528 if (!empty($content) && !in_array($name, $twitter_order, true)) {
1529 + // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- esc_meta_value() applies esc_url()/esc_attr(); the sniff cannot follow a method call.
932 1530 echo '<meta name="' . esc_attr($name) . '" content="' . $this->esc_meta_value($name, $content) . '" />' . "\n";
933 1531 }
934 1532 }
935 1533
@@ -963,8 +1561,16 @@
963 1561 *
964 1562 * @return void
965 1563 */
966 1564 public function output_platform_meta_tags(): void {
1565 + // Same reasoning as the Open Graph and Twitter emitters: an error page
1566 + // has no shareable identity, and passing '404' through as a social
1567 + // context asks the manager for settings that describe a page which does
1568 + // not exist. Guarding all three keeps them from disagreeing.
1569 + if ($this->current_context === '404') {
1570 + return;
1571 + }
1572 +
967 1573 // Try Social Meta Manager for platform tags
968 1574 if ($this->social_manager) {
969 1575 // Map context for Social Meta Manager (homepage -> site for site-wide settings)
970 1576 $social_context = $this->current_context === 'homepage' ? 'site' : $this->current_context;
@@ -1016,8 +1622,23 @@
1016 1622 *
1017 1623 * @return void
1018 1624 */
1019 1625 public function output_open_graph_tags(): void {
1626 + // Per-content-type Open Graph switch. 'inherit' (the default) keeps the
1627 + // site-wide Social Media setting, which the emitters below read (#660).
1628 + if (!\ThinkRank\SEO\Content_Type_Settings::is_enabled_for_current(
1629 + \ThinkRank\SEO\Content_Type_Settings::FEATURE_OPEN_GRAPH,
1630 + true
1631 + )) {
1632 + return;
1633 + }
1634 +
1635 + // An error page has no shareable identity. Emitting Open Graph here
1636 + // advertised the homepage as the og:url of a URL that does not exist.
1637 + if ($this->current_context === '404') {
1638 + return;
1639 + }
1640 +
1020 1641 // Priority 1: Try Social Meta Manager (Social Media tab settings)
1021 1642 if ($this->social_manager) {
1022 1643 // Map context for Social Meta Manager (homepage -> site for site-wide settings)
1023 1644 $social_context = $this->current_context === 'homepage' ? 'site' : $this->current_context;
@@ -1038,9 +1659,12 @@
1038 1659 // The Social Meta Manager ran, so it owns Open Graph output. If OG is
1039 1660 // toggled off, emit nothing — do NOT fall through to the basic
1040 1661 // emitter (which would re-add a full OG block despite the toggle).
1041 1662 if (!empty($social_data['og_enabled'])) {
1042 - $this->output_social_og_tags($social_data['og_tags']);
1663 + $this->output_social_og_tags(
1664 + $social_data['og_tags'],
1665 + $social_data['og_extra_images'] ?? []
1666 + );
1043 1667 }
1044 1668 return;
1045 1669 }
1046 1670
@@ -1068,8 +1692,21 @@
1068 1692 (string) get_post_meta($this->current_post_id, '_thinkrank_og_description', true),
1069 1693 $this->current_post_id
1070 1694 );
1071 1695 $og_image_override = get_post_meta($this->current_post_id, '_thinkrank_og_image', true);
1696 + } elseif ($this->current_term_id) {
1697 + // Terms carry the same social override keys — the abilities API
1698 + // writes them — so honour them here rather than letting the term's
1699 + // SEO title stand in for an explicit og:title.
1700 + $og_title_override = \ThinkRank\SEO\Pattern_Resolver::resolve_term_value(
1701 + (string) get_term_meta($this->current_term_id, '_thinkrank_og_title', true),
1702 + $this->current_term_id
1703 + );
1704 + $og_description_override = \ThinkRank\SEO\Pattern_Resolver::resolve_term_value(
1705 + (string) get_term_meta($this->current_term_id, '_thinkrank_og_description', true),
1706 + $this->current_term_id
1707 + );
1708 + $og_image_override = get_term_meta($this->current_term_id, '_thinkrank_og_image', true);
1072 1709 }
1073 1710
1074 1711 // Get title using priority system: OG override > post-specific > Global SEO > Site Identity > default
1075 1712 $title = '';
@@ -1090,10 +1727,14 @@
1090 1727 $description = $og_description_override;
1091 1728 } else {
1092 1729 $description = $this->get_meta_description();
1093 1730 }
1094 - if (!$description) {
1095 - $description = is_singular() ? wp_trim_words(get_the_excerpt(), 30) : get_bloginfo('description');
1731 + // Skipped for a protected post: core answers get_the_excerpt() with its
1732 + // "There is no excerpt because this is a protected post." placeholder,
1733 + // so this is not a leak — but publishing that sentence as the social
1734 + // description is worse than publishing none (#363).
1735 + if (!$description && !$this->is_content_password_protected()) {
1736 + $description = is_singular() ? \ThinkRank\Core\Seo_Text::trim_words(get_the_excerpt(), 30) : get_bloginfo('description');
1096 1737 }
1097 1738
1098 1739 $url = is_singular() ? get_permalink() : home_url();
1099 1740 $site_name = $this->site_identity_data && !empty($this->site_identity_data['identity']['site_name'])
@@ -1121,11 +1762,11 @@
1121 1762 $og_type = apply_filters('thinkrank_og_type', $og_type);
1122 1763
1123 1764 echo "<!-- ThinkRank SEO Open Graph Meta Tags -->\n";
1124 1765 echo "<meta property=\"og:type\" content=\"" . esc_attr($og_type) . "\" />\n";
1125 - echo "<meta property=\"og:title\" content=\"" . esc_attr($title) . "\" />\n";
1766 + echo "<meta property=\"og:title\" content=\"" . esc_attr(self::strip_title_tags($title)) . "\" />\n";
1126 1767 echo "<meta property=\"og:description\" content=\"" . esc_attr($description) . "\" />\n";
1127 - echo "<meta property=\"og:url\" content=\"" . esc_url($url) . "\" />\n";
1768 + echo "<meta property=\"og:url\" content=\"" . esc_url(\ThinkRank\SEO\Url_Scheme::apply($url)) . "\" />\n";
1128 1769 echo "<meta property=\"og:site_name\" content=\"" . esc_attr($site_name) . "\" />\n";
1129 1770 /**
1130 1771 * Filter the og:locale value.
1131 1772 *
@@ -1142,14 +1783,17 @@
1142 1783 $og_locale = (string) apply_filters('thinkrank_og_locale', get_locale());
1143 1784 echo "<meta property=\"og:locale\" content=\"" . esc_attr($og_locale) . "\" />\n";
1144 1785
1145 1786 // Add OG image — per-post override > featured image
1787 + $primary_og_image = '';
1146 1788 if (is_singular() && $this->current_post_id) {
1147 1789 if (!empty($og_image_override)) {
1790 + $primary_og_image = (string) $og_image_override;
1148 1791 echo "<meta property=\"og:image\" content=\"" . esc_url($og_image_override) . "\" />\n";
1149 1792 echo "<meta property=\"og:image:secure_url\" content=\"" . esc_url($og_image_override) . "\" />\n";
1150 1793 } elseif (has_post_thumbnail($this->current_post_id)) {
1151 1794 $image_url = get_the_post_thumbnail_url($this->current_post_id, 'large');
1795 + $primary_og_image = (string) $image_url;
1152 1796 echo "<meta property=\"og:image\" content=\"" . esc_url($image_url) . "\" />\n";
1153 1797 echo "<meta property=\"og:image:secure_url\" content=\"" . esc_url($image_url) . "\" />\n";
1154 1798
1155 1799 // Get image dimensions and alt text
@@ -1155,12 +1799,16 @@
1155 1799 // Get image dimensions and alt text
1156 1800 $image_id = get_post_thumbnail_id($this->current_post_id);
1157 1801 $image_meta = wp_get_attachment_metadata($image_id);
1158 1802 if ($image_meta) {
1803 + // The `large` file being published, not the original it
1804 + // was generated from: the metadata's own width and height
1805 + // describe an image this tag does not point at (#847).
1806 + $image_file = \ThinkRank\SEO\Attachment_Lookup::describe((int) $image_id, (string) $image_url);
1159 1807 // SVGs (and other vector uploads) report 0x0 — emitting
1160 1808 // those as og:image dimensions is invalid, so skip them.
1161 - $og_width = isset($image_meta['width']) ? (int) $image_meta['width'] : 0;
1162 - $og_height = isset($image_meta['height']) ? (int) $image_meta['height'] : 0;
1809 + $og_width = $image_file['width'];
1810 + $og_height = $image_file['height'];
1163 1811 if ($og_width > 0 && $og_height > 0) {
1164 1812 echo "<meta property=\"og:image:width\" content=\"" . esc_attr($og_width) . "\" />\n";
1165 1813 echo "<meta property=\"og:image:height\" content=\"" . esc_attr($og_height) . "\" />\n";
1166 1814 }
@@ -1165,9 +1813,9 @@
1165 1813 echo "<meta property=\"og:image:height\" content=\"" . esc_attr($og_height) . "\" />\n";
1166 1814 }
1167 1815 // Derive the real mime type instead of hardcoding image/jpeg,
1168 1816 // which mislabels PNG/WebP featured images.
1169 - $image_mime = get_post_mime_type($image_id);
1817 + $image_mime = $image_file['type'];
1170 1818 if ($image_mime) {
1171 1819 echo "<meta property=\"og:image:type\" content=\"" . esc_attr($image_mime) . "\" />\n";
1172 1820 }
1173 1821 }
@@ -1178,8 +1826,30 @@
1178 1826 echo "<meta property=\"og:image:alt\" content=\"" . esc_attr($image_alt) . "\" />\n";
1179 1827 }
1180 1828 }
1181 1829
1830 + // Alternatives, same as the enhanced emitter above. This path only
1831 + // runs when the Social Meta Manager is unavailable, but the issue
1832 + // reported against it (#636) and a site that lands here should not
1833 + // silently lose a feature it switched on.
1834 + if (!empty($primary_og_image)) {
1835 + $social_settings = $this->social_manager
1836 + ? $this->social_manager->get_settings(
1837 + $this->current_context === 'homepage' ? 'site' : $this->current_context,
1838 + $this->current_post_id
1839 + )
1840 + : [];
1841 +
1842 + if (!empty($social_settings['og_multiple_images'])) {
1843 + self::output_extra_og_images(
1844 + \ThinkRank\SEO\Social_Images::additional(
1845 + (int) $this->current_post_id,
1846 + $primary_og_image
1847 + )
1848 + );
1849 + }
1850 + }
1851 +
1182 1852 // Add article specific tags for posts only
1183 1853 if ($og_type === 'article') {
1184 1854 echo '<meta property="article:published_time" content="' . esc_attr(get_the_date('c', $this->current_post_id)) . '" />' . "\n";
1185 1855 echo '<meta property="article:modified_time" content="' . esc_attr(get_the_modified_date('c', $this->current_post_id)) . '" />' . "\n";
@@ -1207,8 +1877,21 @@
1207 1877 *
1208 1878 * @return void
1209 1879 */
1210 1880 public function output_twitter_card_tags(): void {
1881 + // Per-content-type Twitter card switch; see output_open_graph_tags().
1882 + if (!\ThinkRank\SEO\Content_Type_Settings::is_enabled_for_current(
1883 + \ThinkRank\SEO\Content_Type_Settings::FEATURE_TWITTER,
1884 + true
1885 + )) {
1886 + return;
1887 + }
1888 +
1889 + // Same reasoning as the Open Graph block: nothing on a 404 is shareable.
1890 + if ($this->current_context === '404') {
1891 + return;
1892 + }
1893 +
1211 1894 // Priority 1: Try Social Meta Manager (Social Media tab settings)
1212 1895 if ($this->social_manager) {
1213 1896 // Map context for Social Meta Manager (homepage -> site for site-wide settings)
1214 1897 $social_context = $this->current_context === 'homepage' ? 'site' : $this->current_context;
@@ -1255,8 +1938,14 @@
1255 1938 $twitter_title_override = \ThinkRank\SEO\Pattern_Resolver::resolve_value((string) get_post_meta($pid, '_thinkrank_twitter_title', true), $pid);
1256 1939 $twitter_description_override = \ThinkRank\SEO\Pattern_Resolver::resolve_value((string) get_post_meta($pid, '_thinkrank_twitter_description', true), $pid);
1257 1940 $og_title_override = \ThinkRank\SEO\Pattern_Resolver::resolve_value((string) get_post_meta($pid, '_thinkrank_og_title', true), $pid);
1258 1941 $og_description_override = \ThinkRank\SEO\Pattern_Resolver::resolve_value((string) get_post_meta($pid, '_thinkrank_og_description', true), $pid);
1942 + } elseif ($this->current_term_id) {
1943 + $tid = $this->current_term_id;
1944 + $twitter_title_override = \ThinkRank\SEO\Pattern_Resolver::resolve_term_value((string) get_term_meta($tid, '_thinkrank_twitter_title', true), $tid);
1945 + $twitter_description_override = \ThinkRank\SEO\Pattern_Resolver::resolve_term_value((string) get_term_meta($tid, '_thinkrank_twitter_description', true), $tid);
1946 + $og_title_override = \ThinkRank\SEO\Pattern_Resolver::resolve_term_value((string) get_term_meta($tid, '_thinkrank_og_title', true), $tid);
1947 + $og_description_override = \ThinkRank\SEO\Pattern_Resolver::resolve_term_value((string) get_term_meta($tid, '_thinkrank_og_description', true), $tid);
1259 1948 }
1260 1949
1261 1950 // Title cascade: Twitter override > OG override > Global SEO > Site Identity > default
1262 1951 $title = '';
@@ -1281,10 +1970,14 @@
1281 1970 $description = $og_description_override;
1282 1971 } else {
1283 1972 $description = $this->get_meta_description();
1284 1973 }
1285 - if (!$description) {
1286 - $description = is_singular() ? wp_trim_words(get_the_excerpt(), 30) : get_bloginfo('description');
1974 + // Skipped for a protected post: core answers get_the_excerpt() with its
1975 + // "There is no excerpt because this is a protected post." placeholder,
1976 + // so this is not a leak — but publishing that sentence as the social
1977 + // description is worse than publishing none (#363).
1978 + if (!$description && !$this->is_content_password_protected()) {
1979 + $description = is_singular() ? \ThinkRank\Core\Seo_Text::trim_words(get_the_excerpt(), 30) : get_bloginfo('description');
1287 1980 }
1288 1981
1289 1982 // Determine card type based on image availability
1290 1983 $card_type = 'summary';
@@ -1293,9 +1986,9 @@
1293 1986 }
1294 1987
1295 1988 echo "<!-- ThinkRank SEO Twitter Card Meta Tags -->\n";
1296 1989 echo '<meta name="twitter:card" content="' . esc_attr($card_type) . '" />' . "\n";
1297 - echo "<meta name=\"twitter:title\" content=\"" . esc_attr($title) . "\" />\n";
1990 + echo "<meta name=\"twitter:title\" content=\"" . esc_attr(self::strip_title_tags($title)) . "\" />\n";
1298 1991 echo "<meta name=\"twitter:description\" content=\"" . esc_attr($description) . "\" />\n";
1299 1992
1300 1993 // Add Twitter image with proper fallback priority
1301 1994 $twitter_image_url = $this->get_twitter_image_with_fallback();
@@ -1345,11 +2038,18 @@
1345 2038 }
1346 2039
1347 2040 if (empty($canonical_url)) {
1348 2041 $canonical_url = $this->current_post_id ? get_permalink($this->current_post_id) : get_permalink();
2042 +
2043 + // Core's rel_canonical() keeps the page number; this replaced
2044 + // it with a bare permalink, so every <!--nextpage--> sub-page
2045 + // and every /comment-page-N/ canonicalised to page 1 — a
2046 + // regression against core behaviour (#397). A custom canonical
2047 + // is left exactly as the user typed it.
2048 + $canonical_url = self::with_singular_page($canonical_url);
1349 2049 }
1350 2050 } else {
1351 - $canonical_url = $this->get_non_singular_canonical_url();
2051 + $canonical_url = self::get_non_singular_canonical_url();
1352 2052 }
1353 2053
1354 2054 /**
1355 2055 * Filter the canonical URL before output.
@@ -1363,14 +2063,115 @@
1363 2063 if (empty($canonical_url)) {
1364 2064 return;
1365 2065 }
1366 2066
2067 + // After the filter, so a canonical an add-on supplied is normalized
2068 + // too — and a cross-domain one is left alone, since Url_Scheme only
2069 + // touches URLs on this site's own host.
2070 + $canonical_url = \ThinkRank\SEO\Url_Scheme::apply($canonical_url);
2071 +
1367 2072 echo "<!-- ThinkRank SEO Canonical URL -->\n";
1368 2073 echo "<link rel=\"canonical\" href=\"" . esc_url($canonical_url) . "\" />\n";
1369 2074 echo "<!-- /ThinkRank SEO Canonical URL -->\n";
2075 +
2076 + $this->output_pagination_links();
1370 2077 }
1371 2078
1372 2079 /**
2080 + * Emit rel="prev" / rel="next" on a paginated archive.
2081 + *
2082 + * Nothing emitted these at all (#397). Google stopped using them as an
2083 + * indexing signal in 2019, so this is not an SEO win with Google — Bing
2084 + * still reads them, and they are the standard way to describe a sequence,
2085 + * which is what the pages are.
2086 + *
2087 + * @since 2.0.1
2088 + *
2089 + * @return void
2090 + */
2091 + private function output_pagination_links(): void {
2092 + // Page 1 still wants a rel="next" when there is a page 2, so only
2093 + // singular views are skipped outright.
2094 + if (is_singular()) {
2095 + return;
2096 + }
2097 +
2098 + global $wp_query;
2099 +
2100 + $total = $wp_query ? (int) $wp_query->max_num_pages : 0;
2101 +
2102 + if ($total < 2) {
2103 + return;
2104 + }
2105 +
2106 + $base = self::get_non_singular_canonical_url();
2107 +
2108 + if ('' === $base) {
2109 + return;
2110 + }
2111 +
2112 + // get_non_singular_canonical_url() already carries the current page —
2113 + // strip it back to page 1 before building the neighbours.
2114 + $current = self::current_page_number();
2115 + $base = self::without_pagination($base);
2116 +
2117 + if ($current > 1) {
2118 + printf(
2119 + "<link rel=\"prev\" href=\"%s\" />\n",
2120 + esc_url(\ThinkRank\SEO\Url_Scheme::apply(self::with_pagination($base, $current - 1)))
2121 + );
2122 + }
2123 +
2124 + if ($current < $total) {
2125 + printf(
2126 + "<link rel=\"next\" href=\"%s\" />\n",
2127 + esc_url(\ThinkRank\SEO\Url_Scheme::apply(self::with_pagination($base, $current + 1)))
2128 + );
2129 + }
2130 + }
2131 +
2132 + /**
2133 + * The rewrite base WordPress uses for page numbers ('page' by default).
2134 + *
2135 + * @since 2.0.1
2136 + *
2137 + * @return string
2138 + */
2139 + private static function pagination_base(): string {
2140 + global $wp_rewrite;
2141 +
2142 + return $wp_rewrite && $wp_rewrite->pagination_base ? $wp_rewrite->pagination_base : 'page';
2143 + }
2144 +
2145 + /**
2146 + * Append the sub-page or comment-page number to a singular canonical.
2147 + *
2148 + * @since 2.0.1
2149 + *
2150 + * @param string $url Permalink.
2151 + * @return string Permalink with the current page appended, when there is one.
2152 + */
2153 + public static function with_singular_page(string $url): string {
2154 + global $wp_rewrite;
2155 +
2156 + $page = (int) get_query_var('page');
2157 +
2158 + if ($page > 1) {
2159 + return $wp_rewrite && $wp_rewrite->using_permalinks()
2160 + ? trailingslashit($url) . user_trailingslashit($page, 'single_paged')
2161 + : add_query_arg('page', $page, $url);
2162 + }
2163 +
2164 + $comment_page = (int) get_query_var('cpage');
2165 +
2166 + if ($comment_page > 1) {
2167 + return get_comments_pagenum_link($comment_page);
2168 + }
2169 +
2170 + return $url;
2171 + }
2172 +
2173 + /**
1373 2174 * Build the canonical URL for non-singular contexts.
1374 2175 *
1375 2176 * Covers the blog home, post type / taxonomy / author / date archives.
1376 2177 * Search results and 404 pages get no canonical (they are noindexed).
@@ -1378,9 +2179,9 @@
1378 2179 * self-referential rather than pointing at page 1.
1379 2180 *
1380 2181 * @return string Canonical URL or '' when none applies
1381 2182 */
1382 - private function get_non_singular_canonical_url(): string {
2183 + public static function get_non_singular_canonical_url(): string {
1383 2184 if (is_404() || is_search()) {
1384 2185 return '';
1385 2186 }
1386 2187
@@ -1411,17 +2212,89 @@
1411 2212 return '';
1412 2213 }
1413 2214
1414 2215 // Point paginated archives at their own page, not page 1.
2216 + return self::with_pagination($canonical_url, (int) get_query_var('paged'));
2217 + }
2218 +
2219 + /**
2220 + * Append a page number to a URL the way WordPress does.
2221 + *
2222 + * Extracted so the archive canonical is not the only thing that knows how
2223 + * to build a paged URL: the schema graph derived its @id from the
2224 + * un-paginated link, so every page of an archive claimed the same node
2225 + * identity, and the singular canonical dropped the page entirely (#397).
2226 + *
2227 + * @since 2.0.1
2228 + *
2229 + * @param string $url Base URL.
2230 + * @param int $page Page number; 1 or less returns the URL unchanged.
2231 + * @return string
2232 + */
2233 + public static function with_pagination(string $url, int $page): string {
2234 + if ($page <= 1 || '' === $url) {
2235 + return $url;
2236 + }
2237 +
2238 + global $wp_rewrite;
2239 +
2240 + if ($wp_rewrite && $wp_rewrite->using_permalinks()) {
2241 + return trailingslashit($url) . user_trailingslashit(
2242 + $wp_rewrite->pagination_base . '/' . $page,
2243 + 'paged'
2244 + );
2245 + }
2246 +
2247 + return add_query_arg('paged', $page, $url);
2248 + }
2249 +
2250 + /**
2251 + * Strip a page number from a URL, whichever form it takes.
2252 + *
2253 + * The inverse of with_pagination(). Pretty permalinks carry the page as a
2254 + * /page/N/ path segment, plain permalinks as a `paged` query arg, and a
2255 + * regex over the path alone silently left the latter in place — so
2256 + * rel="prev" on page 2 pointed at page 2 (#397 review).
2257 + *
2258 + * @since 2.0.1
2259 + *
2260 + * @param string $url URL that may carry a page number.
2261 + * @return string URL for page 1.
2262 + */
2263 + public static function without_pagination(string $url): string {
2264 + if ('' === $url) {
2265 + return $url;
2266 + }
2267 +
2268 + $url = remove_query_arg('paged', $url);
2269 +
2270 + return (string) preg_replace(
2271 + '#/' . preg_quote(self::pagination_base(), '#') . '/\d+/?$#',
2272 + '/',
2273 + $url
2274 + );
2275 + }
2276 +
2277 + /**
2278 + * The page number of the current request, archive or multi-page post.
2279 + *
2280 + * `paged` counts archive pages; `page` counts the <!--nextpage--> parts of
2281 + * a single post. They are never both set.
2282 + *
2283 + * @since 2.0.1
2284 + *
2285 + * @return int Page number, 1 when this is the first page.
2286 + */
2287 + public static function current_page_number(): int {
1415 2288 $paged = (int) get_query_var('paged');
2289 +
1416 2290 if ($paged > 1) {
1417 - global $wp_rewrite;
1418 - $canonical_url = $wp_rewrite->using_permalinks()
1419 - ? trailingslashit($canonical_url) . user_trailingslashit($wp_rewrite->pagination_base . '/' . $paged, 'paged')
1420 - : add_query_arg('paged', $paged, $canonical_url);
2291 + return $paged;
1421 2292 }
1422 2293
1423 - return $canonical_url;
2294 + $page = (int) get_query_var('page');
2295 +
2296 + return $page > 1 ? $page : 1;
1424 2297 }
1425 2298
1426 2299
1427 2300 /**
@@ -1429,12 +2302,13 @@
1429 2302 *
1430 2303 * @return bool True if has ThinkRank metadata
1431 2304 */
1432 2305 private function has_thinkrank_metadata(): bool {
1433 - if (!is_singular()) {
1434 - return false;
1435 - }
1436 -
2306 + // Populated by initialize_current_context() for singular views and for
2307 + // term archives, and left empty everywhere else — so the emptiness
2308 + // check is the whole test. The `!is_singular()` early return this
2309 + // replaced is what made every stored term title and description inert:
2310 + // the entire title/description cascade hangs off this method (#386).
1437 2311 return !empty($this->current_metadata['title']) || !empty($this->current_metadata['description']);
1438 2312 }
1439 2313
1440 2314 /**
@@ -1568,12 +2442,21 @@
1568 2442
1569 2443 // Get excerpt
1570 2444 $post = get_post($this->current_post_id);
1571 2445 if ($post) {
1572 - $excerpt = !empty($post->post_excerpt)
1573 - ? $post->post_excerpt
1574 - : wp_trim_words(wp_strip_all_tags($post->post_content), 25, '...');
1575 - $placeholders['%excerpt%'] = $excerpt;
2446 + // An authored post_excerpt is written for public consumption, so
2447 + // it stays. Falling back to the body does not: for a protected
2448 + // post that derivation leaks the gated content through any
2449 + // template containing %excerpt%, and this branch runs BEFORE the
2450 + // derive-from-content priority below, so guarding only that one
2451 + // would leave this path open (#363).
2452 + if (!empty($post->post_excerpt)) {
2453 + $placeholders['%excerpt%'] = $post->post_excerpt;
2454 + } elseif (!$this->is_content_password_protected($post->ID)) {
2455 + $placeholders['%excerpt%'] = \ThinkRank\SEO\Pattern_Resolver::derive_excerpt(
2456 + \ThinkRank\SEO\Builder_Content::visible_content($post)
2457 + );
2458 + }
1576 2459 }
1577 2460
1578 2461 // Get author
1579 2462 $author_id = get_post_field('post_author', $this->current_post_id);
@@ -1633,8 +2516,17 @@
1633 2516 $settings = $this->site_identity_manager->get_settings('site');
1634 2517
1635 2518 switch ($this->current_context) {
1636 2519 case 'homepage':
2520 + // detect_current_context() collapses the static posts page into
2521 + // 'homepage', so it rendered the front page's title template and
2522 + // the two pages shipped the same <title> — a duplicate title on
2523 + // the site's two most-linked URLs (#397 review). It is a page,
2524 + // and it has its own name, so it gets the page template.
2525 + if (self::is_static_posts_page()) {
2526 + return $settings['page_title'] ?? $settings['homepage_title'] ?? null;
2527 + }
2528 +
1637 2529 return $settings['homepage_title'] ?? null;
1638 2530 case 'post':
1639 2531 return $settings['post_title'] ?? null;
1640 2532 case 'page':
@@ -1665,12 +2557,18 @@
1665 2557 $settings = $this->site_identity_manager->get_settings('site');
1666 2558 $separator = $this->get_title_separator($settings['title_separator'] ?? 'pipe');
1667 2559
1668 2560 $placeholders = [
1669 - '%site_title%' => $settings['site_name'] ?? get_bloginfo('name'),
1670 - '%site_name%' => $settings['site_name'] ?? get_bloginfo('name'),
1671 - '%site_description%' => $settings['site_description'] ?? get_bloginfo('description'),
1672 - '%tagline%' => $settings['tagline'] ?? get_bloginfo('description'),
2561 + // first_non_empty(), not `??`: Site Identity persists these as ''
2562 + // rather than leaving them unset, and '' is not null — so the
2563 + // null-coalesce stopped dead on the empty string and the WordPress
2564 + // fallback was unreachable. A site with a tagline set in Settings →
2565 + // General rendered "%site_description%" as nothing (#398). This is
2566 + // the same reasoning first_non_empty()'s own docblock records.
2567 + '%site_title%' => $this->first_non_empty($settings['site_name'] ?? '', get_bloginfo('name')),
2568 + '%site_name%' => $this->first_non_empty($settings['site_name'] ?? '', get_bloginfo('name')),
2569 + '%site_description%' => $this->first_non_empty($settings['site_description'] ?? '', get_bloginfo('description')),
2570 + '%tagline%' => $this->first_non_empty($settings['tagline'] ?? '', get_bloginfo('description')),
1673 2571 '%separator%' => ' ' . $separator . ' ',
1674 2572 '%sep%' => ' ' . $separator . ' ',
1675 2573 '%date%' => gmdate('F Y'),
1676 2574 ];
@@ -1723,10 +2621,26 @@
1723 2621 $placeholders['%search_term%'] = get_search_query();
1724 2622 break;
1725 2623
1726 2624 case 'archive':
1727 - $placeholders['%archive_title%'] = get_the_archive_title();
2625 + // Stripped: get_the_archive_title() wraps its subject in a
2626 + // <span>, and this placeholder feeds the document <title> as
2627 + // well as og:title and twitter:title — a date archive rendered
2628 + // as "Month: <span>August 2026</span> | Site".
2629 + $placeholders['%archive_title%'] = self::archive_subject();
1728 2630 break;
2631 +
2632 + case 'homepage':
2633 + // The page template resolved for a static posts page needs the
2634 + // page's own name; without it %title%/%page_title% would render
2635 + // empty and collapse back to the site title.
2636 + if (self::is_static_posts_page()) {
2637 + $posts_page_title = get_the_title((int) get_option('page_for_posts'));
2638 + $placeholders['%title%'] = $posts_page_title;
2639 + $placeholders['%page_title%'] = $posts_page_title;
2640 + $placeholders['%post_title%'] = $posts_page_title;
2641 + }
2642 + break;
1729 2643 }
1730 2644
1731 2645 return $placeholders;
1732 2646 }
@@ -1731,8 +2645,19 @@
1731 2645 return $placeholders;
1732 2646 }
1733 2647
1734 2648 /**
2649 + * Whether this request is a static posts page rather than the front page.
2650 + *
2651 + * @since 2.0.1
2652 + *
2653 + * @return bool
2654 + */
2655 + private static function is_static_posts_page(): bool {
2656 + return is_home() && !is_front_page() && (int) get_option('page_for_posts') > 0;
2657 + }
2658 +
2659 + /**
1735 2660 * Process title template with placeholders
1736 2661 *
1737 2662 * @param string $template Template string
1738 2663 * @param array $placeholders Placeholder values
@@ -1769,8 +2694,42 @@
1769 2694 return \ThinkRank\SEO\Site_Identity_Manager::$title_separators[$separator_type]['symbol'] ?? \ThinkRank\SEO\Site_Identity_Manager::$title_separators['pipe']['symbol'];
1770 2695 }
1771 2696
1772 2697 /**
2698 + * Whether a post's body must not be read for a public surface.
2699 + *
2700 + * Deriving metadata from `post_content` publishes that content to everyone
2701 + * who requests the URL — and to every crawler and link-preview unfurler
2702 + * that reads og:description — while the page itself still shows only the
2703 + * password form, so the leak is invisible to the site owner (#363).
2704 + *
2705 + * This is the one thing every content reader should call before touching
2706 + * `post_content` for output. It mirrors core: a visitor who has already
2707 + * entered the correct password sees the body anyway, so nothing is hidden
2708 + * from them here either.
2709 + *
2710 + * @param int|null $post_id Optional. Post ID. Defaults to the current post.
2711 + * @return bool True when the body is password-gated for this visitor.
2712 + */
2713 + private function is_content_password_protected(?int $post_id = null): bool {
2714 + $post_id = $post_id ?? $this->current_post_id;
2715 +
2716 + if (!$post_id) {
2717 + return false;
2718 + }
2719 +
2720 + $post = get_post($post_id);
2721 +
2722 + if (!$post) {
2723 + return false;
2724 + }
2725 +
2726 + // Guarded for the same reason the schema path guards it: this class is
2727 + // also exercised outside a full front-end request.
2728 + return function_exists('post_password_required') && post_password_required($post);
2729 + }
2730 +
2731 + /**
1773 2732 * Get meta description with fallback system
1774 2733 * Priority: Post-specific metadata > Global SEO templates > Site Identity templates > WordPress defaults
1775 2734 *
1776 2735 * @return string|null Meta description or null if none available
@@ -1803,13 +2762,23 @@
1803 2762 return $default_description;
1804 2763 }
1805 2764 }
1806 2765
1807 - // Fourth priority: Generate from content for posts/pages
1808 - if (is_singular() && $this->current_post_id) {
1809 - $post_content = get_post_field('post_content', $this->current_post_id);
2766 + // Fourth priority: Generate from content for posts/pages.
2767 + // Never for a password-protected post — deriving the description from a
2768 + // gated body published its first ~25 words in the page head, and the
2769 + // same value is reused for og:description and twitter:description, so
2770 + // one unguarded read leaked through three tags (#363).
2771 + if (is_singular() && $this->current_post_id && !$this->is_content_password_protected()) {
2772 + // Not the raw column: a Bricks page discards `post_content`, so
2773 + // whatever is still stored there is invisible — and this one value
2774 + // becomes the meta, og: and twitter: descriptions (#651).
2775 + $described = get_post($this->current_post_id);
2776 + $post_content = $described instanceof \WP_Post
2777 + ? \ThinkRank\SEO\Builder_Content::visible_content($described)
2778 + : get_post_field('post_content', $this->current_post_id);
1810 2779 if ($post_content) {
1811 - $excerpt = wp_trim_words(wp_strip_all_tags($post_content), 25, '...');
2780 + $excerpt = \ThinkRank\SEO\Pattern_Resolver::derive_excerpt((string) $post_content);
1812 2781 if (!empty($excerpt)) {
1813 2782 return $excerpt;
1814 2783 }
1815 2784 }
@@ -1853,11 +2822,13 @@
1853 2822 if ($description === '') {
1854 2823 return null;
1855 2824 }
1856 2825
1857 - if (strlen($description) > 160) {
1858 - $description = wp_trim_words($description, 25, '...');
1859 - }
2826 + // Measure and cut in CHARACTERS. strlen() counts bytes, so a Thai or
2827 + // CJK description tripped this limit at a third of its length, and
2828 + // wp_trim_words() then cut by a unit the locale chooses — 25 words in
2829 + // English, 25 characters in Thai (#687).
2830 + $description = \ThinkRank\Core\Seo_Text::trim_to_length($description);
1860 2831
1861 2832 return $description;
1862 2833 }
1863 2834
@@ -1904,11 +2875,13 @@
1904 2875 $description = preg_replace('/\s+/', ' ', $description);
1905 2876 $description = trim($description);
1906 2877
1907 2878 // Ensure description doesn't exceed recommended length (160 characters)
1908 - if (strlen($description) > 160) {
1909 - $description = wp_trim_words($description, 25, '...');
1910 - }
2879 + // Measure and cut in CHARACTERS. strlen() counts bytes, so a Thai or
2880 + // CJK description tripped this limit at a third of its length, and
2881 + // wp_trim_words() then cut by a unit the locale chooses — 25 words in
2882 + // English, 25 characters in Thai (#687).
2883 + $description = \ThinkRank\Core\Seo_Text::trim_to_length($description);
1911 2884
1912 2885 return $description;
1913 2886 }
1914 2887
@@ -1922,8 +2895,19 @@
1922 2895 public function output_site_schema_markup(): void {
1923 2896 $has_schema_manager_output = false;
1924 2897 $has_website_schema = false;
1925 2898
2899 + // The master switch on Essential SEO -> Schema Manager. Until #461 this
2900 + // was never read here, so turning schema off left every deployed entity
2901 + // on the page. Read it once and bail before touching the graph.
2902 + if ($this->schema_manager) {
2903 + $schema_settings = $this->schema_manager->get_settings('site', null);
2904 +
2905 + if (isset($schema_settings['enabled']) && !$schema_settings['enabled']) {
2906 + return;
2907 + }
2908 + }
2909 +
1926 2910 // PRIORITY 1: Always output site-wide schemas (Organization, Website, LocalBusiness, Person)
1927 2911 if ($this->schema_manager) {
1928 2912 $site_wide_schemas = $this->schema_manager->get_deployed_schemas('site', null);
1929 2913
@@ -1928,9 +2912,9 @@
1928 2912 $site_wide_schemas = $this->schema_manager->get_deployed_schemas('site', null);
1929 2913
1930 2914 if (!empty($site_wide_schemas)) {
1931 2915 foreach ($site_wide_schemas as $schema_type => $schema_info) {
1932 - $this->output_schema_markup($schema_info['data'], $schema_type, 'Schema Manager');
2916 + Schema_Graph::instance()->add_supporting($schema_info['data'], (string) $schema_type);
1933 2917 }
1934 2918 $has_schema_manager_output = true;
1935 2919 $has_website_schema = isset($site_wide_schemas['WebSite']);
1936 2920 }
@@ -1951,9 +2935,9 @@
1951 2935 */
1952 2936 $website_schema = apply_filters('thinkrank_website_schema', $website_schema);
1953 2937
1954 2938 if (!empty($website_schema)) {
1955 - $this->output_schema_markup($website_schema, 'WebSite', 'Site Identity');
2939 + Schema_Graph::instance()->add_supporting($website_schema, 'WebSite');
1956 2940 }
1957 2941 }
1958 2942
1959 2943 // PRIORITY 2: Also output page-specific schemas (Article, HowTo, FAQ, etc.) on individual posts/pages
@@ -1959,15 +2943,24 @@
1959 2943 // PRIORITY 2: Also output page-specific schemas (Article, HowTo, FAQ, etc.) on individual posts/pages
1960 2944 if ($this->schema_manager && (is_single() || is_page())) {
1961 2945 $context_id = get_the_ID();
1962 2946 $context_type = get_post_type( $context_id );
1963 - $context_type = in_array( $context_type, [ 'site', 'post', 'page', 'product' ] ) ? $context_type : 'post';
2947 + $context_type = in_array( $context_type, [ 'site', 'post', 'page', 'product' ] , true) ? $context_type : 'post';
1964 2948
1965 2949 $page_specific_schemas = $this->schema_manager->get_deployed_schemas($context_type, $context_id);
1966 2950
1967 2951 if (!empty($page_specific_schemas)) {
1968 - // Apply filter for Pro to allow multiple schemas
1969 - // In free version, it's limited to 1 schema if not filtered
2952 + // Every deployed schema is rendered, on every plan. How many a
2953 + // page carries is decided when schemas are activated in the
2954 + // editor, not trimmed here by plan (#673).
2955 +
2956 + /**
2957 + * Filter the page-specific schemas rendered on the current page.
2958 + *
2959 + * @param array $page_specific_schemas Deployed schemas keyed by schema type.
2960 + * @param string $context_type Context type (post, page, product, site).
2961 + * @param int $context_id Post ID.
2962 + */
1970 2963 $page_specific_schemas = apply_filters(
1971 2964 'thinkrank_page_schemas_to_render',
1972 2965 $page_specific_schemas,
1973 2966 $context_type,
@@ -1973,21 +2966,37 @@
1973 2966 $context_type,
1974 2967 $context_id
1975 2968 );
1976 2969
1977 - // If still multiple schemas and not Pro, limit to 1 (enforcing free limit)
1978 - $is_pro = \ThinkRank\Core\Plan_Config::is_pro();
1979 - if (!$is_pro && count($page_specific_schemas) > 2) {
1980 - $page_specific_schemas = array_slice($page_specific_schemas, 0, 2, true);
1981 - }
2970 + // A deployed node is a snapshot from Deploy time and outranks
2971 + // the automatic node, so page and article types would publish
2972 + // a frozen excerpt instead of the description the head
2973 + // resolves. Give them the live one, as the automatic node has.
2974 + $context_post = get_post($context_id);
1982 2975
1983 2976 foreach ($page_specific_schemas as $schema_type => $schema_info) {
1984 - $this->output_schema_markup($schema_info['data'], $schema_type, 'Schema Manager');
2977 + $node = $schema_info['data'];
2978 +
2979 + if ($this->global_seo_schema && $context_post instanceof \WP_Post) {
2980 + $node = $this->global_seo_schema->refresh_deployed_description($node, (string) $schema_type, $context_post);
2981 + }
2982 +
2983 + Schema_Graph::instance()->add_primary($node, (string) $schema_type, 'schema_manager');
1985 2984 }
1986 2985 $has_schema_manager_output = true;
1987 2986 }
1988 2987 }
1989 2988
2989 + // Absorb FAQ content from the post body (FAQ block / Elementor widget)
2990 + // so it merges into the graph's single FAQPage instead of each producer
2991 + // emitting its own competing one.
2992 + if (is_singular()) {
2993 + $queried_post = get_post();
2994 + if ($queried_post instanceof \WP_Post) {
2995 + Schema_Graph::instance()->collect_post_faq($queried_post);
2996 + }
2997 + }
2998 +
1990 2999 // Skip Site Identity fallback if any Schema Manager schemas were output
1991 3000 if ($has_schema_manager_output) {
1992 3001 return;
1993 3002 }
@@ -2006,9 +3015,9 @@
2006 3015
2007 3016 $schema = $this->generate_organization_schema($settings);
2008 3017
2009 3018 if ($schema) {
2010 - $this->output_schema_markup($schema, 'Organization', 'Site Identity');
3019 + Schema_Graph::instance()->add_supporting($schema, 'Organization');
2011 3020 }
2012 3021 }
2013 3022
2014 3023 /**
@@ -2030,42 +3039,50 @@
2030 3039 'url' => home_url('/'),
2031 3040 ];
2032 3041
2033 3042 $description = !empty($settings['site_description']) ? $settings['site_description'] : get_bloginfo('description');
3043 + // The tagline is stored esc_html()'d by sanitize_option(), so a site
3044 + // called "Fish & Chips" published `&amp;` literally in its WebSite
3045 + // node; nothing decodes JSON-LD downstream.
3046 + $description = \ThinkRank\Core\Seo_Text::normalize_schema_text((string) $description);
2034 3047 if (!empty($description)) {
2035 3048 $schema['description'] = $description;
2036 3049 }
2037 3050
2038 - $schema['potentialAction'] = [
2039 - '@type' => 'SearchAction',
2040 - 'target' => [
2041 - '@type' => 'EntryPoint',
2042 - 'urlTemplate' => home_url('/?s={search_term_string}'),
2043 - ],
2044 - 'query-input' => 'required name=search_term_string',
2045 - ];
3051 + // Site Identity has accepted an alternate name since the setup wizard
3052 + // shipped, and the MCP ability describes it as "published as schema
3053 + // alternateName" — but no producer ever read it, so the promise was
3054 + // false and every imported Yoast/Rank Math value sat unused (#692).
3055 + $alternate_name = \ThinkRank\SEO\Site_Identity_Manager::alternate_name_for_schema($settings['alternate_name'] ?? null);
3056 + if (null !== $alternate_name) {
3057 + $schema['alternateName'] = $alternate_name;
3058 + }
2046 3059
2047 - return $schema;
2048 - }
3060 + // The sitelinks searchbox switch was honoured only for a deployed
3061 + // WebSite row; this live fallback added potentialAction unconditionally,
3062 + // so website_enable_search = 0 still shipped the SearchAction (#688).
3063 + // Absent means not configured, which stays enabled.
3064 + $search_enabled = true;
3065 + if ($this->schema_manager) {
3066 + $schema_settings = $this->schema_manager->get_settings('site', null);
2049 3067
2050 - /**
2051 - * Output schema markup with consistent formatting
2052 - *
2053 - * @param array $schema_data Schema data
2054 - * @param string $schema_type Schema type name
2055 - * @param string $source Source of schema (Schema Manager, Site Identity, etc.)
2056 - * @return void
2057 - */
2058 - private function output_schema_markup(array $schema_data, string $schema_type, string $source): void {
2059 - if (empty($schema_data)) {
2060 - return;
3068 + if (array_key_exists('website_enable_search', $schema_settings)) {
3069 + $search_enabled = !empty($schema_settings['website_enable_search']);
3070 + }
2061 3071 }
2062 3072
2063 - echo '<!-- ThinkRank ' . esc_html($source) . ': ' . esc_html($schema_type) . ' Schema -->' . "\n";
2064 - echo '<script type="application/ld+json">' . "\n";
2065 - echo wp_json_encode($schema_data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . "\n";
2066 - echo '</script>' . "\n";
2067 - echo '<!-- /ThinkRank ' . esc_html($source) . ': ' . esc_html($schema_type) . ' Schema -->' . "\n";
3073 + if ($search_enabled) {
3074 + $schema['potentialAction'] = [
3075 + '@type' => 'SearchAction',
3076 + 'target' => [
3077 + '@type' => 'EntryPoint',
3078 + 'urlTemplate' => home_url('/?s={search_term_string}'),
3079 + ],
3080 + 'query-input' => 'required name=search_term_string',
3081 + ];
3082 + }
3083 +
3084 + return $schema;
2068 3085 }
2069 3086
2070 3087 /**
2071 3088 * Generate organization schema markup
@@ -2261,8 +3278,15 @@
2261 3278 if (!$this->site_identity_data || !$this->site_identity_data['enabled']) {
2262 3279 return;
2263 3280 }
2264 3281
3282 + // A breadcrumb trail for a URL that does not exist, or for a search
3283 + // results page, describes nothing — and the plugin already emits no
3284 + // canonical on either (#471).
3285 + if (is_404() || is_search()) {
3286 + return;
3287 + }
3288 +
2265 3289 $settings = $this->site_identity_manager->get_settings('site');
2266 3290
2267 3291 // Only output if breadcrumbs are enabled
2268 3292 if (empty($settings['breadcrumbs_enabled'])) {
@@ -2268,42 +3292,74 @@
2268 3292 if (empty($settings['breadcrumbs_enabled'])) {
2269 3293 return;
2270 3294 }
2271 3295
3296 + // Schema Manager's own breadcrumb switch. Only Site Identity's
3297 + // breadcrumbs_enabled was consulted here, so enable_breadcrumbs_schema
3298 + // = 0 removed a deployed BreadcrumbList row and left this live one
3299 + // emitting the node anyway (#688). Absent means not configured, which
3300 + // stays enabled.
3301 + if ($this->schema_manager) {
3302 + $schema_settings = $this->schema_manager->get_settings('site', null);
3303 +
3304 + if (array_key_exists('enable_breadcrumbs_schema', $schema_settings)
3305 + && empty($schema_settings['enable_breadcrumbs_schema'])) {
3306 + return;
3307 + }
3308 + }
3309 +
2272 3310 $breadcrumbs = $this->generate_breadcrumbs($settings);
2273 3311
2274 3312 if (!empty($breadcrumbs['schema'])) {
2275 - echo "<!-- ThinkRank SEO Breadcrumb Schema Markup -->\n";
2276 - echo '<script type="application/ld+json">' . "\n";
2277 - echo wp_json_encode($breadcrumbs['schema'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . "\n";
2278 - echo '</script>' . "\n";
2279 - echo "<!-- /ThinkRank SEO Breadcrumb Schema Markup -->\n";
3313 + Schema_Graph::instance()->add_supporting($breadcrumbs['schema'], 'BreadcrumbList');
2280 3314 }
2281 3315 }
2282 3316
2283 3317 /**
3318 + * Emit everything ThinkRank collected for this request as one linked @graph.
3319 + *
3320 + * Runs after every producer has registered (site schema 7, breadcrumbs 8,
3321 + * Global SEO 15), so the graph can arbitrate between them.
3322 + *
3323 + * @since 1.32.0
3324 + * @return void
3325 + */
3326 + public function output_schema_graph(): void {
3327 + Schema_Graph::instance()->render();
3328 + }
3329 +
3330 + /**
2284 3331 * Output closing comment for ThinkRank SEO
2285 3332 *
2286 3333 * @return void
2287 3334 */
2288 3335 public function output_closing_comment(): void {
2289 - // Only output if we've output any SEO content
2290 - static $header_output = false;
2291 - if ($header_output || $this->has_seo_output()) {
3336 + // Close only what was actually opened. has_seo_output() is true on
3337 + // nearly every page, so testing it here printed a closing comment with
3338 + // no matching opener whenever the meta description was empty (search
3339 + // results, author archives without a description).
3340 + if (self::$opening_comment_output) {
2292 3341 echo "<!-- /ThinkRank SEO -->\n";
2293 3342 }
2294 3343 }
2295 3344
2296 3345 /**
2297 - * Check if any SEO content has been output
3346 + * Print the opening ThinkRank comment, once per request.
2298 3347 *
2299 - * @return bool True if SEO content was output
3348 + * Public and static so Author_Archives_Manager — which prints its own meta
3349 + * description on wp_head at priority 5 — opens the block through the same
3350 + * flag the closing comment reads.
3351 + *
3352 + * @since 2.0.1
3353 + * @return void
2300 3354 */
2301 - private function has_seo_output(): bool {
2302 - // Check if we have meta description or any other SEO data
2303 - return !empty($this->get_meta_description()) ||
2304 - $this->has_thinkrank_metadata() ||
2305 - ($this->site_identity_data && $this->site_identity_data['enabled']);
3355 + public static function note_opening_comment(): void {
3356 + if (self::$opening_comment_output) {
3357 + return;
3358 + }
3359 +
3360 + echo "<!-- Search Engine Optimization by ThinkRank - https://thinkrank.ai/ -->\n";
3361 + self::$opening_comment_output = true;
2306 3362 }
2307 3363
2308 3364 /**
2309 3365 * Display breadcrumbs HTML
@@ -2497,15 +3553,158 @@
2497 3553 return $breadcrumbs;
2498 3554 }
2499 3555
2500 3556 /**
3557 + * Serve /llms.txt through PHP so the response declares UTF-8.
3558 + *
3559 + * Cheap guard first: every other front-end request leaves without loading
3560 + * the manager.
3561 + *
3562 + * @since 1.32.0
3563 + *
3564 + * @return void
3565 + */
3566 + /**
3567 + * Serve a ThinkRank sitemap document for this request, when it is one.
3568 + *
3569 + * Only acts in dynamic delivery mode. In static mode a real file exists and
3570 + * the web server returns it without WordPress ever loading, so answering
3571 + * here as well would mean two sources for the same bytes.
3572 + *
3573 + * @since 2.9.0
3574 + *
3575 + * @return void
3576 + */
3577 + public function maybe_serve_sitemap(): void {
3578 + $filename = $this->requested_sitemap_filename();
3579 + if ('' === $filename) {
3580 + return;
3581 + }
3582 +
3583 + try {
3584 + // Read-only instance: passing false keeps it from registering a
3585 + // second copy of the auto-generation hooks.
3586 + $generator = new \ThinkRank\SEO\Sitemap_Generator(false);
3587 + $settings = $generator->get_settings('site');
3588 +
3589 + if (empty($settings['enabled'])) {
3590 + return;
3591 + }
3592 +
3593 + if ('dynamic' !== $generator->resolve_delivery_mode($settings)) {
3594 + return;
3595 + }
3596 +
3597 + if (!$generator->publishes_document_name($filename, $settings)) {
3598 + return;
3599 + }
3600 +
3601 + $xml = $generator->render_document($filename, $settings);
3602 + } catch (\Throwable $e) {
3603 + // A failed render must not replace the sitemap with a fatal. Leave
3604 + // the request alone so WordPress answers as it otherwise would.
3605 + return;
3606 + }
3607 +
3608 + if (!is_string($xml) || '' === trim($xml)) {
3609 + return;
3610 + }
3611 +
3612 + status_header(200);
3613 + header('Content-Type: application/xml; charset=UTF-8');
3614 + header('X-Robots-Tag: noindex, follow', true);
3615 +
3616 + // Built XML, escaped by the builders as they assemble it; escaping the
3617 + // document here would corrupt it.
3618 + echo $xml; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
3619 + exit;
3620 + }
3621 +
3622 + /**
3623 + * The sitemap file name this request is asking for, if it looks like one.
3624 + *
3625 + * Deliberately a cheap shape test. Whether the site actually publishes the
3626 + * name is settled by the caller against the generator, so that a request
3627 + * for someone else's sitemap is never answered here.
3628 + *
3629 + * @since 2.9.0
3630 + *
3631 + * @return string File name, or '' when this is not a sitemap request.
3632 + */
3633 + private function requested_sitemap_filename(): string {
3634 + if (empty($_SERVER['REQUEST_URI'])) {
3635 + return '';
3636 + }
3637 +
3638 + $path = wp_parse_url(sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])), PHP_URL_PATH);
3639 + if (!is_string($path) || '' === $path) {
3640 + return '';
3641 + }
3642 +
3643 + // Strip the install's home path so subdirectory installs match too.
3644 + $home_path = (string) wp_parse_url(home_url('/'), PHP_URL_PATH);
3645 + if ('' !== $home_path && '/' !== $home_path && 0 === strpos($path, $home_path)) {
3646 + $path = substr($path, strlen($home_path));
3647 + }
3648 +
3649 + $candidate = strtolower(trim($path, '/'));
3650 +
3651 + // One path segment ending in .xml. Anything nested is not a file we
3652 + // publish to the web root.
3653 + if ('' === $candidate || strpos($candidate, '/') !== false) {
3654 + return '';
3655 + }
3656 +
3657 + return substr($candidate, -4) === '.xml' ? $candidate : '';
3658 + }
3659 +
3660 + public function maybe_serve_llms_txt(): void {
3661 + if (!$this->is_llms_txt_request()) {
3662 + return;
3663 + }
3664 +
3665 + if (!class_exists('ThinkRank\\SEO\\LLMs_Txt_Manager')) {
3666 + require_once THINKRANK_PLUGIN_DIR . 'includes/seo/class-llms-txt-manager.php';
3667 + }
3668 +
3669 + $manager = new \ThinkRank\SEO\LLMs_Txt_Manager();
3670 + $manager->serve_llms_txt();
3671 + }
3672 +
3673 + /**
3674 + * Whether the current request is for /llms.txt.
3675 + *
3676 + * @since 1.32.0
3677 + *
3678 + * @return bool
3679 + */
3680 + private function is_llms_txt_request(): bool {
3681 + if (empty($_SERVER['REQUEST_URI'])) {
3682 + return false;
3683 + }
3684 +
3685 + $path = wp_parse_url(sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])), PHP_URL_PATH);
3686 + if (!is_string($path) || '' === $path) {
3687 + return false;
3688 + }
3689 +
3690 + // Strip the install's home path so subdirectory installs match too.
3691 + $home_path = (string) wp_parse_url(home_url('/'), PHP_URL_PATH);
3692 + if ('' !== $home_path && '/' !== $home_path && 0 === strpos($path, $home_path)) {
3693 + $path = substr($path, strlen($home_path));
3694 + }
3695 +
3696 + return 'llms.txt' === strtolower(trim($path, '/'));
3697 + }
3698 +
3699 + /**
2501 3700 * Filter WordPress robots.txt output
2502 3701 *
2503 3702 * @param string $output The default robots.txt output
2504 - * @param string $public Whether the site is public
3703 + * @param string $is_public Whether the site is public
2505 3704 * @return string Modified robots.txt content
2506 3705 */
2507 - public function filter_robots_txt(string $output, string $public): string {
3706 + public function filter_robots_txt(string $output, string $is_public): string {
2508 3707 // Only override if Site Identity is enabled and robots.txt management is enabled
2509 3708 if (!$this->site_identity_data || !$this->site_identity_data['enabled']) {
2510 3709 return $output;
2511 3710 }
@@ -2531,8 +3730,190 @@
2531 3730 return $output;
2532 3731 }
2533 3732
2534 3733 /**
3734 + * Disable WordPress core's sitemap while ThinkRank's sitemap is enabled.
3735 + *
3736 + * Prevents the site from publishing two competing sitemap indexes. Core's
3737 + * /wp-sitemap.xml is taken offline (it 404s) and, as a consequence, core
3738 + * stops adding its own "Sitemap:" directive to robots.txt — including on the
3739 + * paths where ThinkRank does not own the robots.txt output.
3740 + *
3741 + * Only ever turns core's sitemap *off*: when ThinkRank's sitemap is disabled
3742 + * the incoming value is returned untouched, so core (or another plugin
3743 + * filtering this) keeps whatever behaviour it already had.
3744 + *
3745 + * @since 1.31.0
3746 + *
3747 + * @param bool $enabled Whether core's sitemap functionality is enabled.
3748 + * @return bool Filtered value.
3749 + */
3750 + public function filter_wp_sitemaps_enabled($enabled): bool {
3751 + return $this->should_disable_core_sitemap() ? false : (bool) $enabled;
3752 + }
3753 +
3754 + /**
3755 + * Redirect the sitemap URLs core owns to the sitemap ThinkRank publishes.
3756 + *
3757 + * Only the *index* route is redirected. Core's per-type children
3758 + * (/wp-sitemap-posts-post-1.xml and friends) are genuinely gone once core is
3759 + * switched off, and a 404 is the honest answer for those; the index is the
3760 + * one URL crawlers and humans actually guess, and the one core's own
3761 + * /sitemap.xml rule funnels into.
3762 + *
3763 + * @since 1.31.0
3764 + *
3765 + * @return void
3766 + */
3767 + public function redirect_core_sitemap_requests(): void {
3768 + if ('index' !== get_query_var('sitemap')) {
3769 + return;
3770 + }
3771 +
3772 + $request_uri = isset($_SERVER['REQUEST_URI'])
3773 + ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI']))
3774 + : '';
3775 +
3776 + $target = $this->resolve_core_sitemap_redirect(
3777 + (string) wp_parse_url($request_uri, PHP_URL_PATH)
3778 + );
3779 +
3780 + if ('' === $target) {
3781 + return;
3782 + }
3783 +
3784 + wp_safe_redirect($target, 301, 'ThinkRank');
3785 + exit;
3786 + }
3787 +
3788 + /**
3789 + * Where a request for one of core's sitemap URLs should be sent, if anywhere.
3790 + *
3791 + * Split out from the hook so the rules are testable without dispatching a
3792 + * request — the caller above is the only part that cannot be (it exits).
3793 + *
3794 + * @since 1.31.0
3795 + *
3796 + * @param string $requested_path Path of the incoming request.
3797 + * @return string Absolute URL to redirect to, or '' to leave the request alone.
3798 + */
3799 + private function resolve_core_sitemap_redirect(string $requested_path): string {
3800 + // Nothing to redirect to unless we have actually taken core offline,
3801 + // which already implies our own sitemap file is on disk.
3802 + if (!$this->should_disable_core_sitemap()) {
3803 + return '';
3804 + }
3805 +
3806 + $target = $this->thinkrank_sitemap_url;
3807 + if ('' === $target) {
3808 + return '';
3809 + }
3810 +
3811 + // Never redirect a URL to itself. A site publishing at /sitemap.xml
3812 + // normally has the web server serve that file before WordPress sees the
3813 + // request, but on a setup where the request does reach PHP this is the
3814 + // difference between a redirect and a loop.
3815 + $destination = (string) wp_parse_url($target, PHP_URL_PATH);
3816 +
3817 + if ('' !== $requested_path && untrailingslashit($requested_path) === untrailingslashit($destination)) {
3818 + return '';
3819 + }
3820 +
3821 + return $target;
3822 + }
3823 +
3824 + /**
3825 + * Whether core's sitemap should be switched off for this site.
3826 + *
3827 + * True when ThinkRank publishes its own sitemap — except in two cases where
3828 + * taking core offline would leave a URL answering nothing:
3829 + *
3830 + * 1. The site is configured to publish *at core's own URL* (the "WordPress
3831 + * Core" preset). Once the static file exists the web server serves it
3832 + * ahead of WordPress anyway, so core can be left alone.
3833 + * 2. ThinkRank's own sitemap file is not on disk yet. Sitemaps here are
3834 + * static files with no dynamic route (see save_sitemap_to_file()), so
3835 + * while the file is missing core's /sitemap.xml -> /wp-sitemap.xml
3836 + * redirect is the only thing answering that URL; suppressing core would
3837 + * turn a recoverable "enabled but not generated" state into a hard 404
3838 + * for crawlers. Core is taken offline as soon as our file appears, so the
3839 + * duplicate-index conflict this filter exists to prevent cannot occur —
3840 + * two indexes are only ever reachable if both are actually published.
3841 + *
3842 + * Once our file does exist, the URLs core stops answering are handed to
3843 + * redirect_core_sitemap_requests() rather than left to 404 — which is why
3844 + * this also resolves the destination.
3845 + *
3846 + * Resolved lazily and memoised: this is consulted from an `init`-time filter
3847 + * on every request, and the underlying settings read is object-cached. The
3848 + * memoisation also keeps the file_exists() call to one per request.
3849 + *
3850 + * @since 1.31.0
3851 + *
3852 + * @return bool True when WordPress core's sitemap should be disabled.
3853 + */
3854 + private function should_disable_core_sitemap(): bool {
3855 + if ($this->thinkrank_sitemap_enabled === null) {
3856 + try {
3857 + // Read-only instance — passing false keeps it from registering a
3858 + // second copy of the save_post/term auto-generation hooks.
3859 + $generator = new \ThinkRank\SEO\Sitemap_Generator(false);
3860 + $settings = $generator->get_settings('site');
3861 +
3862 + // "Can ThinkRank actually answer its sitemap URL right now?" In
3863 + // static mode that means the file is on disk; in dynamic mode
3864 + // maybe_serve_sitemap() answers it, so there is nothing to look
3865 + // for. Keeping the file test as the only answer would have left
3866 + // core's sitemap in place on every dynamic site, which is the
3867 + // crawl conflict this suppression exists to prevent (#752).
3868 + // The #346 behaviour is unchanged: a static site with nothing
3869 + // published still falls through to core rather than 404ing.
3870 + $can_serve = 'dynamic' === $generator->resolve_delivery_mode($settings)
3871 + || $generator->primary_sitemap_file_exists($settings);
3872 +
3873 + $this->thinkrank_sitemap_enabled = !empty($settings['enabled'])
3874 + && !$this->publishes_at_core_sitemap_url($settings)
3875 + && $can_serve;
3876 +
3877 + if ($this->thinkrank_sitemap_enabled) {
3878 + $this->thinkrank_sitemap_url = $generator->get_primary_sitemap_url($settings);
3879 + }
3880 + } catch (\Exception $e) {
3881 + // Settings unreadable — leave core's sitemap alone rather than
3882 + // removing a working sitemap on the strength of a failed read.
3883 + $this->thinkrank_sitemap_enabled = false;
3884 + $this->thinkrank_sitemap_url = '';
3885 + }
3886 + }
3887 +
3888 + return $this->thinkrank_sitemap_enabled;
3889 + }
3890 +
3891 + /**
3892 + * Whether any configured sitemap URL is WordPress core's own wp-sitemap.xml.
3893 + *
3894 + * @since 1.31.0
3895 + *
3896 + * @param array $settings Sitemap settings.
3897 + * @return bool True when the site publishes at core's sitemap URL.
3898 + */
3899 + private function publishes_at_core_sitemap_url(array $settings): bool {
3900 + foreach ((array) ($settings['sitemap_urls'] ?? []) as $sitemap) {
3901 + if (!is_array($sitemap)) {
3902 + continue;
3903 + }
3904 +
3905 + $path = (string) wp_parse_url((string) ($sitemap['url'] ?? ''), PHP_URL_PATH);
3906 +
3907 + if (ltrim($path, '/') === 'wp-sitemap.xml') {
3908 + return true;
3909 + }
3910 + }
3911 +
3912 + return false;
3913 + }
3914 +
3915 + /**
2535 3916 * Re-sync the physical robots.txt when WordPress's "Discourage search
2536 3917 * engines" setting (blog_public) changes.
2537 3918 *
2538 3919 * Only acts when ThinkRank robots management is enabled AND a physical
@@ -2582,15 +3963,17 @@
2582 3963 if (empty($settings['enabled'])) {
2583 3964 return (string) $url;
2584 3965 }
2585 3966
3967 + $size = (int) $size;
3968 +
2586 3969 // Apple touch icon has its own dedicated setting
2587 - if ((int) $size === 180 && !empty($settings['apple_touch_icon_url'])) {
2588 - return esc_url($settings['apple_touch_icon_url']);
3970 + if ($size === 180 && !empty($settings['apple_touch_icon_url'])) {
3971 + return $this->resolve_icon_url((string) $settings['apple_touch_icon_url'], $size);
2589 3972 }
2590 3973
2591 3974 if (!empty($settings['favicon_url'])) {
2592 - return esc_url($settings['favicon_url']);
3975 + return $this->resolve_icon_url((string) $settings['favicon_url'], $size);
2593 3976 }
2594 3977
2595 3978 return (string) $url;
2596 3979 }
@@ -2595,8 +3978,178 @@
2595 3978 return (string) $url;
2596 3979 }
2597 3980
2598 3981 /**
3982 + * Whether breadcrumb labels should prefer the SEO title.
3983 + *
3984 + * Off unless the site turns it on, so updating the plugin never rewrites an
3985 + * existing trail.
3986 + *
3987 + * @since 2.3.1
3988 + *
3989 + * @param array $settings Breadcrumb settings.
3990 + * @return bool
3991 + */
3992 + private function breadcrumbs_use_seo_title(array $settings): bool {
3993 + return !empty($settings['breadcrumb_use_seo_title']);
3994 + }
3995 +
3996 + /**
3997 + * Label for a post in the breadcrumb trail.
3998 + *
3999 + * With the toggle on, the post's own SEO title wins — the same
4000 + * `_thinkrank_seo_title` value (variable tags resolved) the document title
4001 + * uses — so the trail under a search snippet reads the same as the snippet
4002 + * itself. Anything empty falls back to the raw post title; the global title
4003 + * pattern is deliberately NOT part of the chain, since resolving it would
4004 + * append the site name to every crumb.
4005 + *
4006 + * @since 2.3.1
4007 + *
4008 + * @param int $post_id Post ID.
4009 + * @param array $settings Breadcrumb settings.
4010 + * @return string Breadcrumb label.
4011 + */
4012 + private function get_breadcrumb_post_title(int $post_id, array $settings): string {
4013 + $title = (string) get_the_title($post_id);
4014 +
4015 + if (!$this->breadcrumbs_use_seo_title($settings)) {
4016 + return $title;
4017 + }
4018 +
4019 + $seo_title = trim((string) get_post_meta($post_id, '_thinkrank_seo_title', true));
4020 +
4021 + if ('' === $seo_title) {
4022 + return $title;
4023 + }
4024 +
4025 + $resolved = trim(\ThinkRank\SEO\Pattern_Resolver::resolve_value($seo_title, $post_id));
4026 +
4027 + return '' !== $resolved ? $resolved : $title;
4028 + }
4029 +
4030 + /**
4031 + * Label for a term in the breadcrumb trail.
4032 + *
4033 + * Term counterpart to {@see self::get_breadcrumb_post_title()}, resolving
4034 + * the term's `_thinkrank_seo_title` against its own values.
4035 + *
4036 + * @since 2.3.1
4037 + *
4038 + * @param object $term Term object.
4039 + * @param array $settings Breadcrumb settings.
4040 + * @return string Breadcrumb label.
4041 + */
4042 + private function get_breadcrumb_term_title($term, array $settings): string {
4043 + $name = (string) ($term->name ?? '');
4044 +
4045 + if (!$this->breadcrumbs_use_seo_title($settings) || empty($term->term_id)) {
4046 + return $name;
4047 + }
4048 +
4049 + $seo_title = trim((string) get_term_meta((int) $term->term_id, '_thinkrank_seo_title', true));
4050 +
4051 + if ('' === $seo_title) {
4052 + return $name;
4053 + }
4054 +
4055 + $resolved = trim(\ThinkRank\SEO\Pattern_Resolver::resolve_term_value($seo_title, (int) $term->term_id));
4056 +
4057 + return '' !== $resolved ? $resolved : $name;
4058 + }
4059 +
4060 + /**
4061 + * Resolve a configured icon URL to the derivative that fits $size.
4062 + *
4063 + * wp_site_icon() calls get_site_icon_url() four times — 32, 192, 180 and
4064 + * 270 — and pairs the first two with a hardcoded sizes="" attribute. This
4065 + * filter used to answer all four with the same configured URL, so one
4066 + * upload was declared as every size at once: a 1536x1536 original served
4067 + * to paint a 32px tab icon, under a sizes="32x32" label that was simply
4068 + * untrue (#571).
4069 + *
4070 + * Resolution mirrors core's own get_site_icon_url(), including the
4071 + * >= 512 -> 'full' branch, so ThinkRank's override and the core pipeline
4072 + * pick the same file for the same request.
4073 + *
4074 + * An unresolvable URL (one hosted off-site) is returned unchanged. Nothing
4075 + * is knowable about its dimensions, and suppressing it instead would leave
4076 + * the page with no rel="icon" at all — a worse outcome than an approximate
4077 + * size hint.
4078 + *
4079 + * @param string $configured Configured icon URL.
4080 + * @param int $size Icon size core is asking for.
4081 + * @return string Icon URL for that size.
4082 + */
4083 + private function resolve_icon_url(string $configured, int $size): string {
4084 + $cache_key = md5($configured) . ':' . $size;
4085 + $cached = $this->icon_urls();
4086 +
4087 + if (isset($cached[$cache_key])) {
4088 + return $cached[$cache_key];
4089 + }
4090 +
4091 + $attachment_id = \ThinkRank\SEO\Site_Identity_Manager::icon_attachment_id($configured);
4092 +
4093 + if (!$attachment_id) {
4094 + $resolved = esc_url($configured);
4095 + } else {
4096 + // Mirrors core: at 512 and above the original is what is wanted, and
4097 + // asking for an intermediate size that large would only fall back to it.
4098 + $size_data = $size >= 512 ? 'full' : [$size, $size];
4099 + $url = wp_get_attachment_image_url($attachment_id, $size_data);
4100 + $resolved = $url ? esc_url($url) : esc_url($configured);
4101 + }
4102 +
4103 + $this->icon_urls[$cache_key] = $resolved;
4104 +
4105 + if (!$this->icon_urls_dirty) {
4106 + $this->icon_urls_dirty = true;
4107 + // Written once, after the response is assembled, rather than once
4108 + // per size: wp_site_icon() resolves four in a row.
4109 + add_action('shutdown', [$this, 'persist_icon_urls'], 5);
4110 + }
4111 +
4112 + return $resolved;
4113 + }
4114 +
4115 + /**
4116 + * The resolved-icon-URL map, loaded from its transient on first use.
4117 + *
4118 + * @return array<string, string>
4119 + */
4120 + private function icon_urls(): array {
4121 + if ($this->icon_urls === null) {
4122 + $stored = get_transient(\ThinkRank\SEO\Site_Identity_Manager::ICON_URL_TRANSIENT);
4123 + $this->icon_urls = is_array($stored) ? $stored : [];
4124 + }
4125 +
4126 + return $this->icon_urls;
4127 + }
4128 +
4129 + /**
4130 + * Persist newly resolved icon URLs.
4131 + *
4132 + * Public because it runs on `shutdown`. Invalidated wholesale whenever the
4133 + * site identity settings are saved, which is the only moment the icon
4134 + * choice — or the derivatives behind it — can change.
4135 + *
4136 + * @return void
4137 + */
4138 + public function persist_icon_urls(): void {
4139 + if (!$this->icon_urls_dirty || !is_array($this->icon_urls)) {
4140 + return;
4141 + }
4142 +
4143 + $this->icon_urls_dirty = false;
4144 + set_transient(
4145 + \ThinkRank\SEO\Site_Identity_Manager::ICON_URL_TRANSIENT,
4146 + $this->icon_urls,
4147 + DAY_IN_SECONDS
4148 + );
4149 + }
4150 +
4151 + /**
2599 4152 * Get breadcrumb items for current page
2600 4153 *
2601 4154 * @param array $settings Breadcrumb settings
2602 4155 * @return array Breadcrumb items
@@ -2624,9 +4177,9 @@
2624 4177 $categories = get_the_category($current_post_id);
2625 4178 if (!empty($categories)) {
2626 4179 $category = $categories[0];
2627 4180 $items[] = [
2628 - 'title' => $category->name,
4181 + 'title' => $this->get_breadcrumb_term_title($category, $settings),
2629 4182 'url' => get_category_link($category->term_id),
2630 4183 'position' => $position++
2631 4184 ];
2632 4185 }
@@ -2631,12 +4184,18 @@
2631 4184 ];
2632 4185 }
2633 4186 }
2634 4187
2635 - // Add current post
2636 - if (empty($settings['show_current_page']) || $settings['show_current_page']) {
4188 + // Add current post. `empty($x) || $x` is true for every possible
4189 + // value — an unset key, false, 0, '' and any truthy value alike —
4190 + // so the setting had no effect on the rendered breadcrumb or on
4191 + // the BreadcrumbList JSON-LD, while the admin preview honoured it
4192 + // and disagreed with live output (#398). Site_Identity_Manager
4193 + // already had the correct form: default to on, respect an
4194 + // explicit off.
4195 + if ($settings['show_current_page'] ?? true) {
2637 4196 $items[] = [
2638 - 'title' => get_the_title($current_post_id),
4197 + 'title' => $this->get_breadcrumb_post_title($current_post_id, $settings),
2639 4198 'url' => get_permalink($current_post_id),
2640 4199 'position' => $position,
2641 4200 'current' => true
2642 4201 ];
@@ -2653,9 +4212,9 @@
2653 4212 while ($parent_id) {
2654 4213 $parent = get_post($parent_id);
2655 4214 if ($parent) {
2656 4215 $parents[] = [
2657 - 'title' => get_the_title($parent->ID),
4216 + 'title' => $this->get_breadcrumb_post_title($parent->ID, $settings),
2658 4217 'url' => get_permalink($parent->ID),
2659 4218 'position' => 0 // Will be set later
2660 4219 ];
2661 4220 $parent_id = $parent->post_parent;
@@ -2673,11 +4232,11 @@
2673 4232 $items[] = $parent;
2674 4233 }
2675 4234
2676 4235 // Add current page
2677 - if (empty($settings['show_current_page']) || $settings['show_current_page']) {
4236 + if ($settings['show_current_page'] ?? true) {
2678 4237 $items[] = [
2679 - 'title' => get_the_title($current_post_id),
4238 + 'title' => $this->get_breadcrumb_post_title($current_post_id, $settings),
2680 4239 'url' => get_permalink($current_post_id),
2681 4240 'position' => $position,
2682 4241 'current' => true
2683 4242 ];
@@ -2693,9 +4252,9 @@
2693 4252 while ($parent_id) {
2694 4253 $parent = get_category($parent_id);
2695 4254 if ($parent && !is_wp_error($parent)) {
2696 4255 $parents[] = [
2697 - 'title' => $parent->name,
4256 + 'title' => $this->get_breadcrumb_term_title($parent, $settings),
2698 4257 'url' => get_category_link($parent->term_id),
2699 4258 'position' => 0 // Will be set later
2700 4259 ];
2701 4260 $parent_id = $parent->parent;
@@ -2713,11 +4272,11 @@
2713 4272 $items[] = $parent;
2714 4273 }
2715 4274
2716 4275 // Add current category
2717 - if (empty($settings['show_current_page']) || $settings['show_current_page']) {
4276 + if ($settings['show_current_page'] ?? true) {
2718 4277 $items[] = [
2719 - 'title' => $category->name,
4278 + 'title' => $this->get_breadcrumb_term_title($category, $settings),
2720 4279 'url' => get_category_link($category->term_id),
2721 4280 'position' => $position,
2722 4281 'current' => true
2723 4282 ];