PluginProbe
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO / 2.9.0
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO v2.9.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 1.0.0 1.0.1 1.0.2 All 50 releases
← All changes | includes/frontend/class-seo-manager.php +2901 -264 1.0.22.9.0 View file →
@@ -1,5 +1,6 @@
1 1 <?php
2 +
2 3 /**
3 4 * Frontend SEO Manager Class
4 5 *
5 6 * Handles frontend SEO meta tag output and WordPress integration
@@ -40,8 +41,16 @@
40 41 */
41 42 private array $current_metadata = [];
42 43
43 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 + /**
44 53 * Site Identity Manager instance
45 54 *
46 55 * @var \ThinkRank\SEO\Site_Identity_Manager|null
47 56 */
@@ -47,8 +56,29 @@
47 56 */
48 57 private ?\ThinkRank\SEO\Site_Identity_Manager $site_identity_manager = null;
49 58
50 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 + /**
51 81 * Social Meta Manager instance
52 82 *
53 83 * @var \ThinkRank\SEO\Social_Meta_Manager|null
54 84 */
@@ -61,8 +91,15 @@
61 91 */
62 92 private ?\ThinkRank\SEO\Schema_Management_System $schema_manager = null;
63 93
64 94 /**
95 + * Global SEO Schema Output instance
96 + *
97 + * @var Global_SEO_Schema_Output|null
98 + */
99 + private ?Global_SEO_Schema_Output $global_seo_schema = null;
100 +
101 + /**
65 102 * Site identity data cache
66 103 *
67 104 * @var array|null
68 105 */
@@ -68,15 +105,61 @@
68 105 */
69 106 private ?array $site_identity_data = null;
70 107
71 108 /**
109 + * Image SEO Manager instance
110 + *
111 + * @var \ThinkRank\SEO\Image_SEO_Manager|null
112 + */
113 + private ?\ThinkRank\SEO\Image_SEO_Manager $image_seo_manager = null;
114 +
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 + /**
72 124 * Current page context
73 125 *
74 126 * @var string
75 127 */
76 128 private string $current_context = 'site';
77 -
129 +
78 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 + /**
79 162 * Initialize SEO manager
80 163 *
81 164 * @return void
82 165 */
@@ -89,14 +172,25 @@
89 172
90 173 // Initialize Schema Manager for enhanced schema output
91 174 $this->initialize_schema_manager();
92 175
93 - // Initialize Google Analytics Tracking Manager
94 - $this->initialize_google_analytics_tracking();
176 + // Initialize Global SEO Schema Output
177 + $this->initialize_global_seo_schema();
95 178
179 + // Initialize Image SEO Manager
180 + $this->initialize_image_seo_manager();
181 +
182 + // Initialize External Links Manager (rel=nofollow / target=_blank)
183 + $this->initialize_external_links_manager();
184 +
96 185 // Initialize current post and context data first
97 186 add_action('wp', [$this, 'initialize_current_context']);
98 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 +
99 193 // Use HIGH PRIORITY hooks to override other SEO plugins
100 194 // Priority 1-5 ensures ThinkRank runs before other SEO plugins
101 195
102 196 // Override WordPress title with HIGH priority
@@ -102,8 +196,20 @@
102 196 // Override WordPress title with HIGH priority
103 197 add_filter('pre_get_document_title', [$this, 'override_document_title'], 1);
104 198 add_filter('wp_title', [$this, 'override_wp_title'], 1, 2);
105 199
200 + // Remove WordPress core's robots output so ours isn't duplicated.
201 + // Core registers wp_robots() on wp_head at priority 1; without this the
202 + // page would emit two <meta name="robots"> tags (core's + ThinkRank's).
203 + // The priority MUST match core's (1) or remove_action is a no-op.
204 + //
205 + // Exception: when "Discourage search engines" is enabled (blog_public=0),
206 + // leave core's wp_robots in place so it emits the native noindex directive,
207 + // and ThinkRank suppresses its own robots tag (see output_seo_meta_tags).
208 + if (get_option('blog_public')) {
209 + remove_action('wp_head', 'wp_robots', 1);
210 + }
211 +
106 212 // Output meta tags with HIGH priority
107 213 add_action('wp_head', [$this, 'output_meta_description'], 1);
108 214 add_action('wp_head', [$this, 'output_seo_meta_tags'], 2);
109 215 add_action('wp_head', [$this, 'output_open_graph_tags'], 3);
@@ -108,13 +214,34 @@
108 214 add_action('wp_head', [$this, 'output_seo_meta_tags'], 2);
109 215 add_action('wp_head', [$this, 'output_open_graph_tags'], 3);
110 216 add_action('wp_head', [$this, 'output_twitter_card_tags'], 4);
111 217 add_action('wp_head', [$this, 'output_platform_meta_tags'], 5);
218 +
219 + // Remove WordPress core's canonical output so ours isn't duplicated.
220 + // Core registers rel_canonical() on wp_head at priority 10; without this
221 + // the page would emit two <link rel="canonical"> tags on singular views.
222 + remove_action('wp_head', 'rel_canonical');
112 223 add_action('wp_head', [$this, 'output_canonical_url'], 6);
113 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 +
114 235 // Add Site Identity specific outputs
115 236 add_action('wp_head', [$this, 'output_site_schema_markup'], 7);
116 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();
117 244
118 245 // Add closing comment (runs last)
119 246 add_action('wp_head', [$this, 'output_closing_comment'], 99);
120 247
@@ -120,10 +247,84 @@
120 247
121 248 // Add breadcrumb display hook
122 249 add_action('thinkrank_breadcrumbs', [$this, 'display_breadcrumbs']);
123 250
251 + // Breadcrumb shortcode for use inside post/page content
252 + add_shortcode('thinkrank_breadcrumbs', [$this, 'breadcrumbs_shortcode']);
253 +
254 + // Hero section (Site Identity → Hero & Branding): theme action hook +
255 + // shortcode so the configured hero title/subtitle/CTA/background render.
256 + add_action('thinkrank_hero', [$this, 'display_hero']);
257 + add_shortcode('thinkrank_hero', [$this, 'hero_shortcode']);
258 +
124 259 // Add robots.txt filter hook
125 260 add_filter('robots_txt', [$this, 'filter_robots_txt'], 10, 2);
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 +
300 + // Keep an existing physical robots.txt in step with WordPress's
301 + // "Discourage search engines" toggle (blog_public). A physical file
302 + // bypasses core's robots_txt filter, so flipping blog_public after the
303 + // file was written would otherwise leave the previous crawl policy served
304 + // until an unrelated robots save. Covers both transitions.
305 + add_action('update_option_blog_public', [$this, 'on_blog_public_changed'], 10, 0);
306 +
307 + // Serve the Site Identity favicon through core's site-icon pipeline so
308 + // wp_site_icon() outputs it on the front-end (and previews pick it up)
309 + add_filter('get_site_icon_url', [$this, 'filter_site_icon_url'], 10, 2);
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 +
320 + // Process image SEO in content
321 + add_filter('the_content', [$this, 'filter_content_images'], 99999);
322 + add_filter('post_thumbnail_html', [$this, 'filter_content_images'], 11, 2);
323 + add_filter('woocommerce_single_product_image_thumbnail_html', [$this, 'filter_content_images'], 11);
324 +
325 + // Persist alt text to the Media Library for newly uploaded images (opt-in).
326 + add_action('add_attachment', [$this, 'maybe_fill_attachment_alt']);
126 327 }
127 328
128 329 /**
129 330 * Initialize Site Identity Manager
@@ -165,22 +366,112 @@
165 366 $this->schema_manager = new \ThinkRank\SEO\Schema_Management_System();
166 367 }
167 368
168 369 /**
169 - * Initialize Google Analytics Tracking Manager
370 + * Initialize Global SEO Schema Output
170 371 *
171 372 * @return void
172 373 */
173 - private function initialize_google_analytics_tracking(): void {
174 - if (!class_exists('ThinkRank\\Frontend\\Google_Analytics_Tracking_Manager')) {
175 - require_once THINKRANK_PLUGIN_DIR . 'includes/frontend/class-google-analytics-tracking-manager.php';
374 + private function initialize_global_seo_schema(): void {
375 + if (!class_exists('ThinkRank\\Frontend\\Global_SEO_Schema_Output')) {
376 + require_once THINKRANK_PLUGIN_DIR . 'includes/frontend/class-global-seo-schema-output.php';
176 377 }
177 378
178 - // Initialize Google Analytics Tracking Manager
179 - new \ThinkRank\Frontend\Google_Analytics_Tracking_Manager();
379 + // Initialize Global SEO Schema Output and store reference
380 + $this->global_seo_schema = new Global_SEO_Schema_Output();
381 + $this->global_seo_schema->init();
180 382 }
181 383
182 384 /**
385 + * Initialize Image SEO Manager
386 + *
387 + * @return void
388 + */
389 + private function initialize_image_seo_manager(): void {
390 + if (!class_exists('ThinkRank\\SEO\\Image_SEO_Manager')) {
391 + require_once THINKRANK_PLUGIN_DIR . 'includes/seo/class-image-seo-manager.php';
392 + }
393 +
394 + $this->image_seo_manager = new \ThinkRank\SEO\Image_SEO_Manager();
395 + }
396 +
397 + /**
398 + * Initialize External Links Manager
399 + *
400 + * @since 2.5.0
401 + * @return void
402 + */
403 + private function initialize_external_links_manager(): void {
404 + if (!class_exists('ThinkRank\\SEO\\External_Links_Manager')) {
405 + require_once THINKRANK_PLUGIN_DIR . 'includes/seo/class-external-links-manager.php';
406 + }
407 +
408 + $this->external_links_manager = new \ThinkRank\SEO\External_Links_Manager();
409 + }
410 +
411 + /**
412 + * Filter rendered content to annotate external links
413 + *
414 + * @since 2.5.0
415 + * @param mixed $content Content to filter; passed through untouched when
416 + * it is not a string.
417 + * @return mixed Filtered content.
418 + */
419 + public function filter_external_links($content) {
420 + // No return type: a filter value another plugin hands through as null
421 + // or an object belongs to whoever set it, and coercing it to '' would
422 + // silently drop their content on the floor.
423 + if (!is_string($content) || $content === '' || !$this->external_links_manager) {
424 + return $content;
425 + }
426 +
427 + // Feeds carry the same markup to a reader we do not control; leave
428 + // them as authored rather than annotating for a context that has no
429 + // browser tab to open.
430 + if (is_feed()) {
431 + return $content;
432 + }
433 +
434 + return $this->external_links_manager->process_content($content);
435 + }
436 +
437 + /**
438 + * Filter content to inject image SEO attributes
439 + *
440 + * @since 1.0.0
441 + * @param string $content Content to filter
442 + * @return string Filtered content
443 + */
444 + public function filter_content_images(string $content, $post_id = null): string {
445 + if (!$this->image_seo_manager) {
446 + return $content;
447 + }
448 +
449 + // Ensure post_id is an integer if provided
450 + if ($post_id !== null && !is_numeric($post_id)) {
451 + $post_id = null;
452 + }
453 +
454 + return $this->image_seo_manager->process_content($content, $post_id ? (int) $post_id : null);
455 + }
456 +
457 + /**
458 + * Persist generated alt text to a freshly uploaded image (opt-in).
459 + *
460 + * Delegates to the Image SEO Manager, which no-ops unless the
461 + * "save alt to media" + "fill on upload" settings are enabled.
462 + *
463 + * @since 1.19.1
464 + * @param int $attachment_id The newly created attachment ID.
465 + * @return void
466 + */
467 + public function maybe_fill_attachment_alt($attachment_id): void {
468 + if ($this->image_seo_manager && is_numeric($attachment_id)) {
469 + $this->image_seo_manager->maybe_auto_fill_on_upload((int) $attachment_id);
470 + }
471 + }
472 +
473 + /**
183 474 * Initialize current context and post data
184 475 *
185 476 * @return void
186 477 */
@@ -196,18 +487,74 @@
196 487 $this->current_metadata = $this->get_post_seo_metadata($post_id);
197 488 }
198 489 }
199 490
491 + // Term archives. Category, tag and custom-taxonomy pages store their SEO
492 + // title and description as term meta — written by the term UI, by the
493 + // abilities API and by the Yoast/RankMath/AIOSEO/SEOPress importer — but
494 + // nothing here ever read them, so the whole title/description cascade
495 + // fell through to the theme default and no description tag was printed
496 + // at all. Term robots was fixed for the same reason in 1.31.0 (#290);
497 + // this is the title and description half (#386).
498 + if (is_category() || is_tag() || is_tax()) {
499 + $queried = get_queried_object();
500 + if ($queried instanceof \WP_Term) {
501 + $this->current_term_id = $queried->term_id;
502 + $this->current_metadata = $this->get_term_seo_metadata($queried->term_id);
503 + }
504 + }
505 +
200 506 // Load site identity data
201 507 $this->load_site_identity_data();
202 508 }
203 509
204 510 /**
511 + * Drop the request's post identity once it has become a 404.
512 + *
513 + * `initialize_current_context()` runs on `wp`, but a request can be turned
514 + * into a 404 after that: `set_404()` on `template_redirect` is the ordinary
515 + * way to refuse a URL that did resolve to a real post, and both core and
516 + * plugins do it — ThinkRank Pro's Markdown for AI refuses an ineligible
517 + * `.md` URL that way. The snapshot still said `post`/`page` and still held
518 + * the post id and its metadata, so the error page shipped that post's meta
519 + * description, focus keywords and — where the social emitters got that far
520 + * — its og:description and twitter:description, all of which a request that
521 + * was a 404 from the start never prints (#655).
522 + *
523 + * Clearing the snapshot rather than special-casing each emitter is what
524 + * makes every consumer agree, including the ones that read
525 + * `$current_metadata` without ever asking what the context is.
526 + *
527 + * @since 2.3.1
528 + *
529 + * @return void
530 + */
531 + public function recheck_404_context(): void {
532 + if (!is_404() || '404' === $this->current_context) {
533 + return;
534 + }
535 +
536 + $this->current_context = '404';
537 + $this->current_post_id = null;
538 + $this->current_term_id = null;
539 + $this->current_metadata = [];
540 + }
541 +
542 + /**
205 543 * Detect current page context
206 544 *
207 545 * @return string Current context type
208 546 */
209 547 private function detect_current_context(): string {
548 + // 404 first: a not-found request matches none of the branches below and
549 + // used to fall through to 'site', which handed crawlers the homepage's
550 + // social identity for an error page. It gets its own context so the
551 + // social layer can skip it, matching get_non_singular_canonical_url(),
552 + // which already suppresses the canonical for 404 and search.
553 + if (is_404()) {
554 + return '404';
555 + }
556 +
210 557 if (is_home() || is_front_page()) {
211 558 return 'homepage';
212 559 } elseif (is_single()) {
213 560 return 'post';
@@ -237,9 +584,9 @@
237 584 if ($this->site_identity_manager && $this->site_identity_data === null) {
238 585 $this->site_identity_data = $this->site_identity_manager->get_output_data('site', null);
239 586 }
240 587 }
241 -
588 +
242 589 /**
243 590 * Get SEO metadata for a post
244 591 *
245 592 * @param int $post_id Post ID
@@ -245,41 +592,213 @@
245 592 * @param int $post_id Post ID
246 593 * @return array SEO metadata
247 594 */
248 595 private function get_post_seo_metadata(int $post_id): array {
596 + $focus_keywords = \ThinkRank\SEO\Focus_Keywords::get($post_id);
597 +
598 + $title = get_post_meta($post_id, '_thinkrank_seo_title', true);
599 + $description = get_post_meta($post_id, '_thinkrank_meta_description', true);
600 +
249 601 return [
250 - 'title' => get_post_meta($post_id, '_thinkrank_seo_title', true),
251 - 'description' => get_post_meta($post_id, '_thinkrank_meta_description', true),
252 - 'focus_keyword' => get_post_meta($post_id, '_thinkrank_focus_keyword', true),
602 + // Per-post values may contain variable tags (e.g. "%title% %sep%
603 + // %sitename%") entered in the metabox, so resolve them. Literal
604 + // values without tags pass through unchanged.
605 + 'title' => $title ? \ThinkRank\SEO\Pattern_Resolver::resolve_value($title, $post_id) : $title,
606 + 'description' => $description ? \ThinkRank\SEO\Pattern_Resolver::resolve_value($description, $post_id) : $description,
607 + 'focus_keyword' => $focus_keywords[0] ?? '',
608 + 'focus_keywords' => $focus_keywords,
253 609 'seo_score' => get_post_meta($post_id, '_thinkrank_seo_score', true),
254 610 ];
255 611 }
256 -
612 +
257 613 /**
614 + * Get SEO metadata for a term.
615 + *
616 + * Mirrors get_post_seo_metadata(): the stored values may carry variable
617 + * tags, so they are resolved against the term's own values. Focus keyword
618 + * and score have no term equivalent on the frontend and stay empty.
619 + *
620 + * @since 2.0.1
621 + *
622 + * @param int $term_id Term ID.
623 + * @return array SEO metadata.
624 + */
625 + private function get_term_seo_metadata(int $term_id): array {
626 + $title = get_term_meta($term_id, '_thinkrank_seo_title', true);
627 + $description = get_term_meta($term_id, '_thinkrank_meta_description', true);
628 +
629 + return [
630 + 'title' => $title
631 + ? \ThinkRank\SEO\Pattern_Resolver::resolve_term_value((string) $title, $term_id)
632 + : '',
633 + 'description' => $description
634 + ? \ThinkRank\SEO\Pattern_Resolver::resolve_term_value((string) $description, $term_id)
635 + : '',
636 + 'focus_keyword' => '',
637 + 'focus_keywords' => [],
638 + 'seo_score' => '',
639 + ];
640 + }
641 +
642 + /**
643 + * Resolve the effective SEO title for the current request.
644 + *
645 + * Same priority chain as override_document_title() — post-specific
646 + * ThinkRank metadata (resolved _thinkrank_seo_title) > Global SEO
647 + * template > Site Identity template — without the raw WordPress-title
648 + * fallback. Returns null when no ThinkRank-managed title applies, letting
649 + * callers (e.g. the social manager OG fallback) drop to their own default.
650 + *
651 + * @return string|null Effective SEO title, or null if none applies.
652 + */
653 + private function get_effective_seo_title(): ?string {
654 + if ($this->has_thinkrank_metadata() && !empty($this->current_metadata['title'])) {
655 + return $this->current_metadata['title'];
656 + }
657 +
658 + return $this->generate_context_title();
659 + }
660 +
661 + /**
258 662 * Override WordPress document title (HIGH PRIORITY)
259 - * Post-specific metadata takes priority over Site Identity templates
663 + * Priority: Post-specific metadata > Global SEO templates > Site Identity templates
260 664 *
261 665 * @param string $title Original title
262 666 * @return string Modified title
263 667 */
264 668 public function override_document_title($title): string {
669 + // A content type with metas switched off keeps whatever title the theme
670 + // and WordPress produce (#660).
671 + if (!$this->metas_enabled()) {
672 + return $title;
673 + }
674 +
265 675 // First priority: Post-specific ThinkRank metadata
266 676 if ($this->has_thinkrank_metadata() && !empty($this->current_metadata['title'])) {
267 - return $this->current_metadata['title'];
677 + return self::with_page_suffix($this->current_metadata['title']);
268 678 }
269 679
270 - // Second priority: Site Identity templates
680 + // Second priority: Global SEO templates, Third priority: Site Identity templates
271 681 $generated_title = $this->generate_context_title();
272 682 if ($generated_title) {
273 - return $generated_title;
683 + return self::with_page_suffix($generated_title);
274 684 }
275 685
276 686 return $title;
277 687 }
278 -
688 +
279 689 /**
690 + * Append a page indicator to a title on page 2 and beyond.
691 + *
692 + * This filter short-circuits pre_get_document_title at priority 1, which
693 + * drops the " – Page 2" core would otherwise add — so every page of an
694 + * archive, and every part of a multi-page post, shared one <title> (#397).
695 + * The templates have no %page% token, so the suffix is added here rather
696 + * than asking every site to edit its title format.
697 + *
698 + * @since 2.0.1
699 + *
700 + * @param string $title Resolved title.
701 + * @return string Title with the page indicator, when there is one.
702 + */
703 + /**
704 + * The archive's subject, without the label WordPress prefixes it with.
705 + *
706 + * `get_the_archive_title()` returns "Month: September 2026", "Archives:
707 + * Recipes", "Category: Uncategorized" — the label is core's, aimed at an
708 + * archive heading on the page, and it reads badly in a browser tab, an
709 + * og:title or a search result. Category, tag and author contexts already
710 + * avoid it by using the raw name; the generic archive context did not, so
711 + * date, custom-post-type and custom-taxonomy archives carried it (#640).
712 + *
713 + * Removed through core's own `get_the_archive_title_prefix` filter rather
714 + * than by matching the prefix text, because that text is translated and
715 + * differs per archive type — a string comparison would work in English and
716 + * silently stop working everywhere else.
717 + *
718 + * A site that wants a prefix can put one in its title template, where it is
719 + * visible and editable, instead of inheriting one it cannot see.
720 + *
721 + * @since 2.7.0
722 + *
723 + * @return string Archive subject, with markup and the core prefix removed.
724 + */
725 + private static function archive_subject(): string {
726 + $drop_prefix = static function (): string {
727 + return '';
728 + };
729 +
730 + add_filter('get_the_archive_title_prefix', $drop_prefix, 99);
731 +
732 + $title = (string) get_the_archive_title();
733 +
734 + remove_filter('get_the_archive_title_prefix', $drop_prefix, 99);
735 +
736 + // The <span> core wraps the subject in survives the prefix filter.
737 + return trim(wp_strip_all_tags($title));
738 + }
739 +
740 + /**
741 + * Remove HTML from a title that is about to be emitted.
742 + *
743 + * A title carrying markup is broken twice over, in two different ways, and
744 + * both were reaching real pages: inside `<title>` the tags render literally,
745 + * because that element is RCDATA and never parses them; inside `og:title`
746 + * and `twitter:title` they are attribute-escaped, so the reader sees
747 + * `&lt;em&gt;` as visible text (#640).
748 + *
749 + * Applied at the point of emission rather than at each source, so it covers
750 + * every branch that can produce a title — post meta, Global SEO templates,
751 + * Site Identity templates — without each having to remember.
752 + *
753 + * Unconditional rather than a setting: there is no title for which markup is
754 + * the correct output. The filter is the escape hatch for anyone who
755 + * disagrees, and lets a site keep entities it deliberately encoded.
756 + *
757 + * @since 2.7.0
758 + *
759 + * @param string $title Title about to be emitted.
760 + * @return string Title with any markup removed.
761 + */
762 + public static function strip_title_tags(string $title): string {
763 + /**
764 + * Filter whether HTML is stripped from generated titles.
765 + *
766 + * @since 2.7.0
767 + *
768 + * @param bool $strip Whether to strip. Default true.
769 + * @param string $title The title being emitted.
770 + */
771 + if (!apply_filters('thinkrank_strip_title_tags', true, $title)) {
772 + return $title;
773 + }
774 +
775 + return trim(wp_strip_all_tags($title));
776 + }
777 +
778 + public static function with_page_suffix(string $title): string {
779 + $title = self::strip_title_tags($title);
780 +
781 + $page = self::current_page_number();
782 +
783 + if ($page <= 1 || '' === $title) {
784 + return $title;
785 + }
786 +
787 + $separator = class_exists('\ThinkRank\SEO\Site_Identity_Manager')
788 + ? \ThinkRank\SEO\Site_Identity_Manager::get_active_separator_symbol()
789 + : '|';
790 +
791 + return $title . ' ' . $separator . ' ' . sprintf(
792 + /* translators: %d: page number. */
793 + __('Page %d', 'thinkrank'),
794 + $page
795 + );
796 + }
797 +
798 + /**
280 799 * Override WordPress wp_title (HIGH PRIORITY)
281 - * Post-specific metadata takes priority over Site Identity templates
800 + * Priority: Post-specific metadata > Global SEO templates > Site Identity templates
282 801 *
283 802 * @param string $title Original title
284 803 * @param string $sep Title separator
285 804 * @return string Modified title
@@ -284,44 +803,79 @@
284 803 * @param string $sep Title separator
285 804 * @return string Modified title
286 805 */
287 806 public function override_wp_title(string $title, string $sep = ''): string {
807 + if (!$this->metas_enabled()) {
808 + return $title;
809 + }
810 +
288 811 // First priority: Post-specific ThinkRank metadata
289 812 if ($this->has_thinkrank_metadata() && !empty($this->current_metadata['title'])) {
290 813 $site_name = get_bloginfo('name');
291 - return $this->current_metadata['title'] . ($sep ? " $sep " : ' | ') . $site_name;
814 + return self::with_page_suffix(
815 + $this->current_metadata['title'] . ($sep ? " $sep " : ' | ') . $site_name
816 + );
292 817 }
293 818
294 - // Second priority: Site Identity templates
819 + // Second priority: Global SEO templates, Third priority: Site Identity templates
295 820 $generated_title = $this->generate_context_title();
296 821 if ($generated_title) {
297 - return $generated_title;
822 + return self::with_page_suffix($generated_title);
298 823 }
299 824
300 825 return $title;
301 826 }
302 -
827 +
303 828 /**
829 + * Whether ThinkRank owns the title and meta description for this request.
830 + *
831 + * Metas are on site-wide by default; the per-content-type matrix can switch
832 + * them off for one content type, in which case ThinkRank stops overriding
833 + * the document title and prints no meta description (#660).
834 + *
835 + * @since 2.5.0
836 + * @return bool
837 + */
838 + private function metas_enabled(): bool {
839 + return \ThinkRank\SEO\Content_Type_Settings::is_enabled_for_current(
840 + \ThinkRank\SEO\Content_Type_Settings::FEATURE_META,
841 + true
842 + );
843 + }
844 +
845 + /**
304 846 * Output meta description (HIGH PRIORITY)
305 - * Uses post-specific metadata or Site Identity default fallback
847 + * Priority: Post-specific metadata > Global SEO templates > Site Identity templates > WordPress defaults
306 848 *
849 + * Author archives are skipped entirely: Author_Archives_Manager owns that
850 + * context and prints its own template-based description on wp_head at
851 + * priority 5. get_archive_meta_description() already declines to build one
852 + * there, but the fallback chain used to continue into the Site Identity
853 + * default, so the page ended up with two <meta name="description"> tags.
854 + *
307 855 * @return void
308 856 */
309 857 public function output_meta_description(): void {
858 + if (is_author()) {
859 + return;
860 + }
861 +
862 + if (!$this->metas_enabled()) {
863 + return;
864 + }
865 +
310 866 $description = $this->get_meta_description();
311 867
312 868 if ($description) {
313 869 // Output main ThinkRank SEO header comment (only once)
314 - static $header_output = false;
315 - if (!$header_output) {
316 - echo "<!-- Search Engine Optimization by ThinkRank - https://thinkrank.ai/ -->\n";
317 - $header_output = true;
318 - }
870 + self::note_opening_comment();
319 871
320 872 // Ensure description is within optimal length (150-160 characters)
321 - if (strlen($description) > 160) {
322 - $description = wp_trim_words($description, 25, '...');
323 - }
873 + // Measure and cut in CHARACTERS. strlen() counts bytes, so a Thai or
874 + // CJK description tripped this limit at a third of its length, and
875 + // wp_trim_words() then cut by a unit the locale chooses — 25 words in
876 + // English, 25 characters in Thai (#687).
877 + $description = \ThinkRank\Core\Seo_Text::trim_to_length($description);
324 878
325 879 echo "<!-- ThinkRank SEO Meta Description -->\n";
326 880 echo '<meta name="description" content="' . esc_attr($description) . '" />' . "\n";
327 881 echo "<!-- /ThinkRank SEO Meta Description -->\n";
@@ -326,9 +880,9 @@
326 880 echo '<meta name="description" content="' . esc_attr($description) . '" />' . "\n";
327 881 echo "<!-- /ThinkRank SEO Meta Description -->\n";
328 882 }
329 883 }
330 -
884 +
331 885 /**
332 886 * Output SEO meta tags
333 887 *
334 888 * @return void
@@ -335,15 +889,24 @@
335 889 */
336 890 public function output_seo_meta_tags(): void {
337 891 echo "<!-- ThinkRank SEO Meta Tags -->\n";
338 892
339 - // Output robots meta tag with proper directives
340 - $robots_content = $this->get_robots_meta_content();
341 - echo '<meta name="robots" content="' . esc_attr($robots_content) . '" />' . "\n";
893 + // Output robots meta tag with proper directives.
894 + // When "Discourage search engines" (blog_public=0) is enabled, defer to
895 + // WordPress core's native noindex output and skip ThinkRank's tag so we
896 + // don't emit a conflicting/duplicate directive.
897 + if (get_option('blog_public')) {
898 + $robots_content = $this->get_robots_meta_content();
899 + echo '<meta name="robots" content="' . esc_attr($robots_content) . '" />' . "\n";
900 + }
342 901
343 - // Output focus keyword as meta keywords (if available and not empty)
344 - if (!empty($this->current_metadata['focus_keyword'])) {
345 - $keywords = trim($this->current_metadata['focus_keyword']);
902 + // Output focus keywords as meta keywords (all keywords, comma-separated)
903 + $focus_keywords = $this->current_metadata['focus_keywords'] ?? [];
904 + if (empty($focus_keywords) && !empty($this->current_metadata['focus_keyword'])) {
905 + $focus_keywords = [$this->current_metadata['focus_keyword']];
906 + }
907 + if (!empty($focus_keywords)) {
908 + $keywords = implode(', ', array_filter(array_map('trim', (array) $focus_keywords), 'strlen'));
346 909 if (!empty($keywords)) {
347 910 echo '<meta name="keywords" content="' . esc_attr($keywords) . '" />' . "\n";
348 911 }
349 912 }
@@ -353,13 +916,41 @@
353 916
354 917 // Output generator meta tag
355 918 echo '<meta name="generator" content="ThinkRank ' . esc_attr(THINKRANK_VERSION) . '" />' . "\n";
356 919
357 - // Output viewport meta tag if not already present
358 - if (!has_action('wp_head', 'wp_site_icon') || !wp_is_mobile()) {
359 - echo '<meta name="viewport" content="width=device-width, initial-scale=1.0" />' . "\n";
920 + // No viewport tag here. The viewport is the theme's responsibility and
921 + // every modern theme ships one, so emitting our own only ever produced a
922 + // second <meta name="viewport"> in the document. The old guard could not
923 + // prevent that either: has_action() returns the registered priority
924 + // (truthy), so its first operand was always false, and !wp_is_mobile() is
925 + // true for every desktop request.
926 + echo "<!-- /ThinkRank SEO Meta Tags -->\n";
927 + }
928 +
929 + /**
930 + * Build the basic robots directive list from a set of robots flags.
931 + *
932 + * Shared by the search/404 branch of get_robots_meta_content() so those
933 + * pages resolve their directives through the same rules as everything else
934 + * rather than a hardcoded literal.
935 + *
936 + * @since 2.5.0
937 + * @param array $settings Robots flags (index/noindex/nofollow/...).
938 + * @return string[] Directives.
939 + */
940 + private static function build_robots_directives(array $settings): array {
941 + $robots = [];
942 +
943 + $robots[] = !empty($settings['noindex']) ? 'noindex' : 'index';
944 + $robots[] = !empty($settings['nofollow']) ? 'nofollow' : 'follow';
945 +
946 + foreach (['noarchive', 'noimageindex', 'nosnippet'] as $directive) {
947 + if (!empty($settings[$directive])) {
948 + $robots[] = $directive;
949 + }
360 950 }
361 - echo "<!-- /ThinkRank SEO Meta Tags -->\n";
951 +
952 + return $robots;
362 953 }
363 954
364 955 /**
365 956 * Get robots meta content based on context and settings
@@ -368,41 +959,312 @@
368 959 */
369 960 private function get_robots_meta_content(): string {
370 961 $robots = [];
371 962
372 - // Default directives
373 - $robots[] = 'index';
374 - $robots[] = 'follow';
963 + // 404 and search results are noindex/follow by default — the behaviour
964 + // that used to be hardcoded here. It is now settings-driven (#660): the
965 + // Content Type Matrix can give either its own robots directives, and an
966 + // install that never touched them resolves to exactly the old pair.
967 + if (is_404() || is_search()) {
968 + $entity = is_404()
969 + ? \ThinkRank\SEO\Content_Type_Settings::ENTITY_404
970 + : \ThinkRank\SEO\Content_Type_Settings::ENTITY_SEARCH;
375 971
972 + $robots = self::build_robots_directives(
973 + \ThinkRank\SEO\Content_Type_Settings::resolve_robots_meta($entity)
974 + );
975 +
976 + $robots = apply_filters('thinkrank_robots_meta', $robots);
977 + return implode(', ', array_unique($robots));
978 + }
979 +
980 + // 1. Get global robot meta settings (Base)
981 + $global_settings = get_option('thinkrank_global_robot_meta_settings', []);
982 +
983 + // Initialize current settings with global defaults
984 + $current_settings = wp_parse_args($global_settings, [
985 + 'index' => true,
986 + 'noindex' => false,
987 + 'nofollow' => false,
988 + 'noarchive' => false,
989 + 'noimageindex' => false,
990 + 'nosnippet' => false,
991 + ]);
992 +
993 + // 2. Apply Post Type based option (if singular)
994 + if (is_singular()) {
995 + $post_type = get_post_type();
996 + $global_seo_settings = get_option('thinkrank_global_seo_settings', []);
997 +
998 + // Check if post type settings are enabled
999 + $robots_enabled = isset($global_seo_settings[$post_type]['robots_meta_enabled']) && $global_seo_settings[$post_type]['robots_meta_enabled'];
1000 +
1001 + if ($robots_enabled && isset($global_seo_settings[$post_type]['robots_meta']) && is_array($global_seo_settings[$post_type]['robots_meta'])) {
1002 + // Merge post type settings over global settings
1003 + $current_settings = array_merge($current_settings, $global_seo_settings[$post_type]['robots_meta']);
1004 + }
1005 + }
1006 +
1007 + // 2b. Apply the per-entity directives for the non-singular content
1008 + // types the matrix covers — taxonomy archives plus author and date
1009 + // archives. Terms keep their own per-term override, applied further
1010 + // down so it still wins over the taxonomy-wide value (#660).
1011 + if (!is_singular()) {
1012 + $entity_key = \ThinkRank\SEO\Content_Type_Settings::current_entity_key();
1013 +
1014 + if ($entity_key !== null) {
1015 + $entity_settings = \ThinkRank\SEO\Content_Type_Settings::get_entity_settings($entity_key);
1016 +
1017 + if (!empty($entity_settings['robots_meta_enabled']) && is_array($entity_settings['robots_meta'] ?? null)) {
1018 + $current_settings = array_merge($current_settings, $entity_settings['robots_meta']);
1019 + }
1020 + }
1021 + }
1022 +
1023 + // Determine Index/Noindex based on merged settings
1024 + // Priority: if noindex is true, it overrides index
1025 + if (!empty($current_settings['noindex'])) {
1026 + $robots[] = 'noindex';
1027 + } else {
1028 + // Default to index if noindex is not set
1029 + $robots[] = 'index';
1030 + }
1031 +
1032 + // Determine Follow/Nofollow based on merged settings
1033 + if (!empty($current_settings['nofollow'])) {
1034 + $robots[] = 'nofollow';
1035 + } else {
1036 + $robots[] = 'follow';
1037 + }
1038 +
1039 + // Other directives
1040 + if (!empty($current_settings['noarchive'])) {
1041 + $robots[] = 'noarchive';
1042 + }
1043 + if (!empty($current_settings['noimageindex'])) {
1044 + $robots[] = 'noimageindex';
1045 + }
1046 + if (!empty($current_settings['nosnippet'])) {
1047 + $robots[] = 'nosnippet';
1048 + }
1049 +
376 1050 // Add advanced directives for better SEO
377 - $robots[] = 'max-snippet:-1';
378 - $robots[] = 'max-image-preview:large';
379 - $robots[] = 'max-video-preview:-1';
1051 + // Get advanced settings
1052 + $advanced_settings = [
1053 + 'snippet_enabled' => true,
1054 + 'max_snippet' => -1,
1055 + 'video_preview_enabled' => true,
1056 + 'max_video_preview' => -1,
1057 + 'image_preview_enabled' => true,
1058 + 'max_image_preview' => 'large'
1059 + ];
380 1060
381 - // Check for specific page settings
1061 + // Apply post type specific advanced settings if enabled
1062 + if (is_singular() && isset($robots_enabled) && $robots_enabled && isset($global_seo_settings[$post_type]['advanced_robots_meta'])) {
1063 + $advanced_settings = array_merge($advanced_settings, $global_seo_settings[$post_type]['advanced_robots_meta']);
1064 + }
1065 +
1066 + // Generate advanced directives
1067 + if (empty($current_settings['nosnippet'])) {
1068 + if ($advanced_settings['snippet_enabled']) {
1069 + $robots[] = 'max-snippet:' . (int)$advanced_settings['max_snippet'];
1070 + }
1071 +
1072 + if ($advanced_settings['video_preview_enabled']) {
1073 + $robots[] = 'max-video-preview:' . (int)$advanced_settings['max_video_preview'];
1074 + }
1075 + }
1076 +
1077 + // Only add max-image-preview if we are allowing image indexing
1078 + if (empty($current_settings['noimageindex']) && $advanced_settings['image_preview_enabled']) {
1079 + $robots[] = 'max-image-preview:' . esc_attr($advanced_settings['max_image_preview']);
1080 + }
1081 +
1082 + // 3. Check for single post meta based option (Overrides everything)
382 1083 if (is_singular()) {
383 - // Check if post has noindex setting
384 - $noindex = get_post_meta(get_the_ID(), '_thinkrank_noindex', true);
385 - if ($noindex) {
386 - $robots = ['noindex', 'nofollow'];
387 - }
1084 + $robots = $this->apply_post_robots_override(get_the_ID(), $robots, $current_settings);
388 1085 }
389 1086
390 - // Check for archive pages
391 - if (is_archive() || is_search()) {
1087 + // Check for archive pages (search is handled by the early return above)
1088 + //
1089 + // is_home() is deliberately included: the blog listing is not an
1090 + // is_archive(), so page 2 of a term archive was noindex while page 2 of
1091 + // the blog listing was index — the same kind of page, treated two
1092 + // different ways, on the same site (#397).
1093 + if (is_archive() || is_home()) {
392 1094 // Allow indexing of category/tag archives but be more conservative
393 1095 if (is_paged()) {
1096 + /**
1097 + * Filter whether a paginated archive is set noindex.
1098 + *
1099 + * Rank Math and Yoast now index paginated archives with a
1100 + * self-referential canonical by default, so a site that wants
1101 + * that can have it without patching.
1102 + *
1103 + * @since 2.0.1
1104 + *
1105 + * @param bool $noindex Whether to noindex this paginated page.
1106 + */
1107 + if (apply_filters('thinkrank_noindex_paged_archives', true)) {
1108 + $robots = ['noindex', 'follow'];
1109 + }
1110 + }
1111 +
1112 + // Honor the global date-archive noindex toggle (written by the
1113 + // Rank Math/Yoast settings importer). Author archives are handled
1114 + // by Author_Archives_Manager via the thinkrank_robots_meta filter.
1115 + if (is_date() && !empty($current_settings['noindex_date_archives'])) {
394 1116 $robots = ['noindex', 'follow'];
395 1117 }
396 1118 }
397 1119
1120 + // 4. Term meta override for taxonomy archives (Overrides everything).
1121 + //
1122 + // Terms had no branch here at all — not a wrong key or a skipped
1123 + // conditional, the lookup simply did not exist — so a category, tag or
1124 + // custom-taxonomy archive saved with noindex still rendered the global
1125 + // default. The stored value read back correctly through the abilities
1126 + // API, which made the setting look applied when it never reached output.
1127 + //
1128 + // Deliberately placed *after* the archive block so it is a real
1129 + // override, matching how a per-post override is final for singular
1130 + // views. Running it earlier would let is_paged() overwrite a term's
1131 + // explicit directives on page 2 of its own archive.
1132 + if (is_category() || is_tag() || is_tax()) {
1133 + $queried = get_queried_object();
1134 + if ($queried instanceof \WP_Term) {
1135 + $robots = $this->apply_term_robots_override($queried->term_id, $robots, $current_settings);
1136 + }
1137 + }
1138 +
398 1139 // Apply filters for customization
399 1140 $robots = apply_filters('thinkrank_robots_meta', $robots);
400 1141
401 - return implode(', ', $robots);
1142 + // Remove duplicates and implode
1143 + return implode(', ', array_unique($robots));
402 1144 }
403 1145
404 1146 /**
1147 + * Apply per-post robots overrides on top of the cascaded directives.
1148 + *
1149 + * Reads `_thinkrank_robots_meta` (JSON) when `_thinkrank_robots_meta_enabled`
1150 + * is truthy. When the override is off, the cascaded directives pass through
1151 + * unchanged.
1152 + *
1153 + * @param int $post_id Post being rendered
1154 + * @param array $robots Directives accumulated so far
1155 + * @param array $current_settings Effective robots flags (global + post type)
1156 + * @return array Updated robots directive list
1157 + */
1158 + private function apply_post_robots_override(int $post_id, array $robots, array $current_settings): array {
1159 + return $this->apply_meta_robots_override(
1160 + (bool) get_post_meta($post_id, '_thinkrank_robots_meta_enabled', true),
1161 + (string) get_post_meta($post_id, '_thinkrank_robots_meta', true),
1162 + (string) get_post_meta($post_id, '_thinkrank_advanced_robots_meta', true),
1163 + $robots,
1164 + $current_settings
1165 + );
1166 + }
1167 +
1168 + /**
1169 + * Apply per-term robots overrides on top of the cascaded directives.
1170 + *
1171 + * The term-meta twin of apply_post_robots_override(). Terms store the same
1172 + * three keys with the same shapes — written by the update-term-seo ability
1173 + * and by the Rank Math / Yoast / AIOSEO / SEOPress importer — so the two
1174 + * paths share one engine rather than a second copy that can drift.
1175 + *
1176 + * @since 1.31.0
1177 + *
1178 + * @param int $term_id Term being rendered
1179 + * @param array $robots Directives accumulated so far
1180 + * @param array $current_settings Effective robots flags (global + post type)
1181 + * @return array Updated robots directive list
1182 + */
1183 + private function apply_term_robots_override(int $term_id, array $robots, array $current_settings): array {
1184 + return $this->apply_meta_robots_override(
1185 + (bool) get_term_meta($term_id, '_thinkrank_robots_meta_enabled', true),
1186 + (string) get_term_meta($term_id, '_thinkrank_robots_meta', true),
1187 + (string) get_term_meta($term_id, '_thinkrank_advanced_robots_meta', true),
1188 + $robots,
1189 + $current_settings
1190 + );
1191 + }
1192 +
1193 + /**
1194 + * Rebuild the robots directives from a stored override, whatever holds it.
1195 + *
1196 + * Kept free of get_post_meta()/get_term_meta() so posts and terms cannot
1197 + * diverge: term support was missing entirely because the only override
1198 + * logic lived behind a post-meta read.
1199 + *
1200 + * @since 1.31.0
1201 + *
1202 + * @param bool $enabled Whether the override is switched on
1203 + * @param string $raw_robots JSON robots flags
1204 + * @param string $raw_advanced JSON advanced directives
1205 + * @param array $robots Directives accumulated so far
1206 + * @param array $current_settings Effective robots flags (global + post type)
1207 + * @return array Updated robots directive list
1208 + */
1209 + private function apply_meta_robots_override(bool $enabled, string $raw_robots, string $raw_advanced, array $robots, array $current_settings): array {
1210 + if (!$enabled) {
1211 + return $robots;
1212 + }
1213 +
1214 + $post_robots = $raw_robots !== '' ? json_decode($raw_robots, true) : null;
1215 + if (!is_array($post_robots)) {
1216 + return $robots;
1217 + }
1218 +
1219 + $post_advanced = $raw_advanced !== '' ? json_decode($raw_advanced, true) : null;
1220 +
1221 + $effective = array_merge($current_settings, array_intersect_key($post_robots, array_flip([
1222 + 'index', 'noindex', 'nofollow', 'noarchive', 'noimageindex', 'nosnippet',
1223 + ])));
1224 +
1225 + $rebuilt = [];
1226 + $rebuilt[] = !empty($effective['noindex']) ? 'noindex' : 'index';
1227 + $rebuilt[] = !empty($effective['nofollow']) ? 'nofollow' : 'follow';
1228 +
1229 + if (!empty($effective['noarchive'])) {
1230 + $rebuilt[] = 'noarchive';
1231 + }
1232 + if (!empty($effective['noimageindex'])) {
1233 + $rebuilt[] = 'noimageindex';
1234 + }
1235 + if (!empty($effective['nosnippet'])) {
1236 + $rebuilt[] = 'nosnippet';
1237 + }
1238 +
1239 + if (is_array($post_advanced)) {
1240 + $advanced = array_merge([
1241 + 'snippet_enabled' => true,
1242 + 'max_snippet' => -1,
1243 + 'video_preview_enabled' => true,
1244 + 'max_video_preview' => -1,
1245 + 'image_preview_enabled' => true,
1246 + 'max_image_preview' => 'large',
1247 + ], $post_advanced);
1248 +
1249 + if (empty($effective['nosnippet'])) {
1250 + if (!empty($advanced['snippet_enabled'])) {
1251 + $rebuilt[] = 'max-snippet:' . (int) $advanced['max_snippet'];
1252 + }
1253 + if (!empty($advanced['video_preview_enabled'])) {
1254 + $rebuilt[] = 'max-video-preview:' . (int) $advanced['max_video_preview'];
1255 + }
1256 + }
1257 +
1258 + if (empty($effective['noimageindex']) && !empty($advanced['image_preview_enabled'])) {
1259 + $rebuilt[] = 'max-image-preview:' . sanitize_text_field((string) $advanced['max_image_preview']);
1260 + }
1261 + }
1262 +
1263 + return $rebuilt;
1264 + }
1265 +
1266 + /**
405 1267 * Output local SEO meta tags for business information
406 1268 *
407 1269 * @return void
408 1270 */
@@ -525,22 +1387,43 @@
525 1387 *
526 1388 * @param array $og_tags Open Graph tags array
527 1389 * @return void
528 1390 */
529 - private function output_social_og_tags(array $og_tags): void {
1391 + private function output_social_og_tags(array $og_tags, array $extra_images = []): void {
1392 + // Honor the thinkrank_og_type filter here too — this "Enhanced" path is
1393 + // the active OG emitter, so add-ons (e.g. Pro's WooCommerce module which
1394 + // sets 'product' on product pages) must be applied to it, not only to
1395 + // output_open_graph_tags().
1396 + if (isset($og_tags['og:type'])) {
1397 + $og_tags['og:type'] = apply_filters('thinkrank_og_type', $og_tags['og:type']);
1398 + }
1399 +
530 1400 echo "<!-- ThinkRank SEO Open Graph Tags (Enhanced) -->\n";
531 1401
532 1402 // Define optimal order for Open Graph tags
533 1403 $og_order = [
534 - 'og:title', 'og:description', 'og:type', 'og:url', 'og:site_name', 'og:locale',
535 - 'og:image', 'og:image:width', 'og:image:height', 'og:image:type', 'og:image:alt',
536 - 'article:published_time', 'article:modified_time', 'article:author', 'article:section'
1404 + 'og:title',
1405 + 'og:description',
1406 + 'og:type',
1407 + 'og:url',
1408 + 'og:site_name',
1409 + 'og:locale',
1410 + 'og:image',
1411 + 'og:image:width',
1412 + 'og:image:height',
1413 + 'og:image:type',
1414 + 'og:image:alt',
1415 + 'article:published_time',
1416 + 'article:modified_time',
1417 + 'article:author',
1418 + 'article:section'
537 1419 ];
538 1420
539 1421 // Output tags in optimal order
540 1422 foreach ($og_order as $property) {
541 1423 if (!empty($og_tags[$property])) {
542 - echo '<meta property="' . esc_attr($property) . '" content="' . esc_attr($og_tags[$property]) . '" />' . "\n";
1424 + // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- esc_meta_value() applies esc_url()/esc_attr(); the sniff cannot follow a method call.
1425 + echo '<meta property="' . esc_attr($property) . '" content="' . $this->esc_meta_value($property, $og_tags[$property]) . '" />' . "\n";
543 1426 }
544 1427 }
545 1428
546 1429 // Output any remaining tags not in the order list
@@ -545,16 +1428,67 @@
545 1428
546 1429 // Output any remaining tags not in the order list
547 1430 foreach ($og_tags as $property => $content) {
548 1431 if (!empty($content) && !in_array($property, $og_order, true)) {
549 - echo '<meta property="' . esc_attr($property) . '" content="' . esc_attr($content) . '" />' . "\n";
1432 + // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- esc_meta_value() applies esc_url()/esc_attr(); the sniff cannot follow a method call.
1433 + echo '<meta property="' . esc_attr($property) . '" content="' . $this->esc_meta_value($property, $content) . '" />' . "\n";
550 1434 }
551 1435 }
552 1436
1437 + // Alternatives, after the primary and everything belonging to it.
1438 + // Order is the whole point: a consumer reads og:image tags in document
1439 + // order and treats the first as primary, and a structured property
1440 + // attaches to the most recently declared image — so each alternative's
1441 + // companions have to follow its own URL, not be grouped at the end.
1442 + self::output_extra_og_images($extra_images);
1443 +
553 1444 echo "<!-- /ThinkRank SEO Open Graph Tags -->\n";
554 1445 }
555 1446
556 1447 /**
1448 + * Emit the secondary og:image tags a page offers.
1449 + *
1450 + * Shared by the enhanced and basic emitters so both describe an
1451 + * alternative image the same way (#636).
1452 + *
1453 + * @since 2.7.0
1454 + *
1455 + * @param array $images Each with url, and width/height/type/alt where known.
1456 + * @return void
1457 + */
1458 + private static function output_extra_og_images(array $images): void {
1459 + foreach ($images as $image) {
1460 + $url = isset($image['url']) ? (string) $image['url'] : '';
1461 +
1462 + if ('' === $url) {
1463 + continue;
1464 + }
1465 +
1466 + echo '<meta property="og:image" content="' . esc_url($url) . '" />' . "\n";
1467 +
1468 + if (strpos($url, 'https://') === 0) {
1469 + echo '<meta property="og:image:secure_url" content="' . esc_url($url) . '" />' . "\n";
1470 + }
1471 +
1472 + // Only what is actually known: a dimension guessed for a remote
1473 + // image is a number a consumer lays a card out with before it has
1474 + // fetched the file.
1475 + if (!empty($image['width']) && !empty($image['height'])) {
1476 + echo '<meta property="og:image:width" content="' . esc_attr((string) $image['width']) . '" />' . "\n";
1477 + echo '<meta property="og:image:height" content="' . esc_attr((string) $image['height']) . '" />' . "\n";
1478 + }
1479 +
1480 + if (!empty($image['type'])) {
1481 + echo '<meta property="og:image:type" content="' . esc_attr((string) $image['type']) . '" />' . "\n";
1482 + }
1483 +
1484 + if (!empty($image['alt'])) {
1485 + echo '<meta property="og:image:alt" content="' . esc_attr((string) $image['alt']) . '" />' . "\n";
1486 + }
1487 + }
1488 + }
1489 +
1490 + /**
557 1491 * Output social media Twitter Card tags from Social Meta Manager
558 1492 *
559 1493 * @param array $twitter_tags Twitter Card tags array
560 1494 * @return void
@@ -563,16 +1497,22 @@
563 1497 echo "<!-- ThinkRank SEO Twitter Card Tags (Enhanced) -->\n";
564 1498
565 1499 // Define optimal order for Twitter Card tags
566 1500 $twitter_order = [
567 - 'twitter:card', 'twitter:title', 'twitter:description', 'twitter:site', 'twitter:creator',
568 - 'twitter:image', 'twitter:image:alt', 'twitter:player', 'twitter:player:width', 'twitter:player:height'
1501 + 'twitter:card',
1502 + 'twitter:title',
1503 + 'twitter:description',
1504 + 'twitter:site',
1505 + 'twitter:creator',
1506 + 'twitter:image',
1507 + 'twitter:image:alt'
569 1508 ];
570 1509
571 1510 // Output tags in optimal order
572 1511 foreach ($twitter_order as $name) {
573 1512 if (!empty($twitter_tags[$name])) {
574 - echo '<meta name="' . esc_attr($name) . '" content="' . esc_attr($twitter_tags[$name]) . '" />' . "\n";
1513 + // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- esc_meta_value() applies esc_url()/esc_attr(); the sniff cannot follow a method call.
1514 + echo '<meta name="' . esc_attr($name) . '" content="' . $this->esc_meta_value($name, $twitter_tags[$name]) . '" />' . "\n";
575 1515 }
576 1516 }
577 1517
578 1518 // Output any remaining tags not in the order list
@@ -577,9 +1517,10 @@
577 1517
578 1518 // Output any remaining tags not in the order list
579 1519 foreach ($twitter_tags as $name => $content) {
580 1520 if (!empty($content) && !in_array($name, $twitter_order, true)) {
581 - echo '<meta name="' . esc_attr($name) . '" content="' . esc_attr($content) . '" />' . "\n";
1521 + // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- esc_meta_value() applies esc_url()/esc_attr(); the sniff cannot follow a method call.
1522 + echo '<meta name="' . esc_attr($name) . '" content="' . $this->esc_meta_value($name, $content) . '" />' . "\n";
582 1523 }
583 1524 }
584 1525
585 1526 echo "<!-- /ThinkRank SEO Twitter Card Tags -->\n";
@@ -585,21 +1526,56 @@
585 1526 echo "<!-- /ThinkRank SEO Twitter Card Tags -->\n";
586 1527 }
587 1528
588 1529 /**
1530 + * Escape a social meta tag value, using esc_url() for URL-valued keys so a
1531 + * javascript:/data: scheme is stripped and output stays spec-compliant, and
1532 + * esc_attr() for everything else.
1533 + *
1534 + * @param string $key The OG/Twitter property or name.
1535 + * @param string|int $value The tag value. Image dimension keys
1536 + * (og:image:width/height) arrive as integers, so
1537 + * accept any scalar and normalise to string here —
1538 + * the file is under strict_types, which would
1539 + * otherwise throw a TypeError on the int.
1540 + * @return string Escaped value.
1541 + */
1542 + private function esc_meta_value(string $key, $value): string {
1543 + $value = (string) $value;
1544 + $url_keys = [
1545 + 'og:image', 'og:image:url', 'og:image:secure_url', 'og:url',
1546 + 'twitter:image', 'twitter:player',
1547 + ];
1548 + return in_array($key, $url_keys, true) ? esc_url($value) : esc_attr($value);
1549 + }
1550 +
1551 + /**
589 1552 * Output platform-specific meta tags
590 1553 *
591 1554 * @return void
592 1555 */
593 1556 public function output_platform_meta_tags(): void {
1557 + // Same reasoning as the Open Graph and Twitter emitters: an error page
1558 + // has no shareable identity, and passing '404' through as a social
1559 + // context asks the manager for settings that describe a page which does
1560 + // not exist. Guarding all three keeps them from disagreeing.
1561 + if ($this->current_context === '404') {
1562 + return;
1563 + }
1564 +
594 1565 // Try Social Meta Manager for platform tags
595 1566 if ($this->social_manager) {
596 1567 // Map context for Social Meta Manager (homepage -> site for site-wide settings)
597 1568 $social_context = $this->current_context === 'homepage' ? 'site' : $this->current_context;
598 1569
1570 + // Pass the same effective title/description as the OG and Twitter
1571 + // callbacks so all three share one memoized get_output_data() result
1572 + // (platform tags don't depend on them, so output is unchanged).
599 1573 $social_data = $this->social_manager->get_output_data(
600 1574 $social_context,
601 - $this->current_post_id
1575 + $this->current_post_id,
1576 + $this->get_effective_seo_title(),
1577 + $this->get_meta_description()
602 1578 );
603 1579
604 1580 if ($social_data['enabled'] && !empty($social_data['platform_tags'])) {
605 1581 $this->output_social_platform_tags($social_data['platform_tags']);
@@ -638,25 +1614,54 @@
638 1614 *
639 1615 * @return void
640 1616 */
641 1617 public function output_open_graph_tags(): void {
1618 + // Per-content-type Open Graph switch. 'inherit' (the default) keeps the
1619 + // site-wide Social Media setting, which the emitters below read (#660).
1620 + if (!\ThinkRank\SEO\Content_Type_Settings::is_enabled_for_current(
1621 + \ThinkRank\SEO\Content_Type_Settings::FEATURE_OPEN_GRAPH,
1622 + true
1623 + )) {
1624 + return;
1625 + }
1626 +
1627 + // An error page has no shareable identity. Emitting Open Graph here
1628 + // advertised the homepage as the og:url of a URL that does not exist.
1629 + if ($this->current_context === '404') {
1630 + return;
1631 + }
1632 +
642 1633 // Priority 1: Try Social Meta Manager (Social Media tab settings)
643 1634 if ($this->social_manager) {
644 1635 // Map context for Social Meta Manager (homepage -> site for site-wide settings)
645 1636 $social_context = $this->current_context === 'homepage' ? 'site' : $this->current_context;
646 1637
1638 + // Effective SEO title/description for this request (resolved
1639 + // per-post value > Global SEO template > Site Identity), identical
1640 + // to what is output as the document <title>/meta description and
1641 + // mirrored by the Social metabox preview. Passed as fallbacks so a
1642 + // cleared Open Graph Title/Description renders the same inherited
1643 + // value the preview shows.
647 1644 $social_data = $this->social_manager->get_output_data(
648 1645 $social_context,
649 - $this->current_post_id
1646 + $this->current_post_id,
1647 + $this->get_effective_seo_title(),
1648 + $this->get_meta_description()
650 1649 );
651 1650
652 - if ($social_data['enabled'] && !empty($social_data['og_tags'])) {
653 - $this->output_social_og_tags($social_data['og_tags']);
654 - return;
1651 + // The Social Meta Manager ran, so it owns Open Graph output. If OG is
1652 + // toggled off, emit nothing — do NOT fall through to the basic
1653 + // emitter (which would re-add a full OG block despite the toggle).
1654 + if (!empty($social_data['og_enabled'])) {
1655 + $this->output_social_og_tags(
1656 + $social_data['og_tags'],
1657 + $social_data['og_extra_images'] ?? []
1658 + );
655 1659 }
1660 + return;
656 1661 }
657 1662
658 - // Priority 2: Fallback to current implementation
1663 + // Priority 2: Fallback only when the Social Meta Manager is unavailable.
659 1664 $this->output_basic_og_tags();
660 1665 }
661 1666
662 1667 /**
@@ -664,11 +1669,43 @@
664 1669 *
665 1670 * @return void
666 1671 */
667 1672 private function output_basic_og_tags(): void {
668 - // Get title using priority system: post-specific > Site Identity > default
1673 + // Check for per-post OG overrides first
1674 + $og_title_override = '';
1675 + $og_description_override = '';
1676 + $og_image_override = '';
1677 + if (is_singular() && $this->current_post_id) {
1678 + // Social fields may hold variable tags entered in the metabox.
1679 + $og_title_override = \ThinkRank\SEO\Pattern_Resolver::resolve_value(
1680 + (string) get_post_meta($this->current_post_id, '_thinkrank_og_title', true),
1681 + $this->current_post_id
1682 + );
1683 + $og_description_override = \ThinkRank\SEO\Pattern_Resolver::resolve_value(
1684 + (string) get_post_meta($this->current_post_id, '_thinkrank_og_description', true),
1685 + $this->current_post_id
1686 + );
1687 + $og_image_override = get_post_meta($this->current_post_id, '_thinkrank_og_image', true);
1688 + } elseif ($this->current_term_id) {
1689 + // Terms carry the same social override keys — the abilities API
1690 + // writes them — so honour them here rather than letting the term's
1691 + // SEO title stand in for an explicit og:title.
1692 + $og_title_override = \ThinkRank\SEO\Pattern_Resolver::resolve_term_value(
1693 + (string) get_term_meta($this->current_term_id, '_thinkrank_og_title', true),
1694 + $this->current_term_id
1695 + );
1696 + $og_description_override = \ThinkRank\SEO\Pattern_Resolver::resolve_term_value(
1697 + (string) get_term_meta($this->current_term_id, '_thinkrank_og_description', true),
1698 + $this->current_term_id
1699 + );
1700 + $og_image_override = get_term_meta($this->current_term_id, '_thinkrank_og_image', true);
1701 + }
1702 +
1703 + // Get title using priority system: OG override > post-specific > Global SEO > Site Identity > default
669 1704 $title = '';
670 - if ($this->has_thinkrank_metadata() && !empty($this->current_metadata['title'])) {
1705 + if (!empty($og_title_override)) {
1706 + $title = $og_title_override;
1707 + } elseif ($this->has_thinkrank_metadata() && !empty($this->current_metadata['title'])) {
671 1708 $title = $this->current_metadata['title'];
672 1709 } else {
673 1710 $title = $this->generate_context_title();
674 1711 }
@@ -675,12 +1712,22 @@
675 1712 if (!$title) {
676 1713 $title = is_singular() ? get_the_title() : get_bloginfo('name');
677 1714 }
678 1715
679 - $description = $this->get_meta_description();
680 - if (!$description) {
681 - $description = is_singular() ? wp_trim_words(get_the_excerpt(), 30) : get_bloginfo('description');
1716 + // Get description with OG override priority
1717 + $description = '';
1718 + if (!empty($og_description_override)) {
1719 + $description = $og_description_override;
1720 + } else {
1721 + $description = $this->get_meta_description();
682 1722 }
1723 + // Skipped for a protected post: core answers get_the_excerpt() with its
1724 + // "There is no excerpt because this is a protected post." placeholder,
1725 + // so this is not a leak — but publishing that sentence as the social
1726 + // description is worse than publishing none (#363).
1727 + if (!$description && !$this->is_content_password_protected()) {
1728 + $description = is_singular() ? \ThinkRank\Core\Seo_Text::trim_words(get_the_excerpt(), 30) : get_bloginfo('description');
1729 + }
683 1730
684 1731 $url = is_singular() ? get_permalink() : home_url();
685 1732 $site_name = $this->site_identity_data && !empty($this->site_identity_data['identity']['site_name'])
686 1733 ? $this->site_identity_data['identity']['site_name']
@@ -695,20 +1742,50 @@
695 1742 } elseif (is_home() || is_front_page()) {
696 1743 $og_type = 'website';
697 1744 }
698 1745
1746 + /**
1747 + * Filter the Open Graph og:type. Add-ons (e.g. ThinkRank Pro's
1748 + * WooCommerce module) use this to set 'product' on product pages.
1749 + *
1750 + * @since 1.14.0
1751 + *
1752 + * @param string $og_type Determined og:type.
1753 + */
1754 + $og_type = apply_filters('thinkrank_og_type', $og_type);
1755 +
699 1756 echo "<!-- ThinkRank SEO Open Graph Meta Tags -->\n";
700 1757 echo "<meta property=\"og:type\" content=\"" . esc_attr($og_type) . "\" />\n";
701 - echo "<meta property=\"og:title\" content=\"" . esc_attr($title) . "\" />\n";
1758 + echo "<meta property=\"og:title\" content=\"" . esc_attr(self::strip_title_tags($title)) . "\" />\n";
702 1759 echo "<meta property=\"og:description\" content=\"" . esc_attr($description) . "\" />\n";
703 - echo "<meta property=\"og:url\" content=\"" . esc_url($url) . "\" />\n";
1760 + echo "<meta property=\"og:url\" content=\"" . esc_url(\ThinkRank\SEO\Url_Scheme::apply($url)) . "\" />\n";
704 1761 echo "<meta property=\"og:site_name\" content=\"" . esc_attr($site_name) . "\" />\n";
705 - echo "<meta property=\"og:locale\" content=\"" . esc_attr(get_locale()) . "\" />\n";
1762 + /**
1763 + * Filter the og:locale value.
1764 + *
1765 + * Defaults to get_locale(), which is only language-correct while the
1766 + * active language's translation files are installed — on a multilingual
1767 + * site without them WordPress keeps reporting the default locale even
1768 + * on translated URLs. The multilingual integration overrides this with
1769 + * the locale its provider reports for the current language.
1770 + *
1771 + * @since 1.23.0
1772 + *
1773 + * @param string $locale Locale for the current request.
1774 + */
1775 + $og_locale = (string) apply_filters('thinkrank_og_locale', get_locale());
1776 + echo "<meta property=\"og:locale\" content=\"" . esc_attr($og_locale) . "\" />\n";
706 1777
707 - // Add featured image if available (only for singular posts/pages)
1778 + // Add OG image — per-post override > featured image
1779 + $primary_og_image = '';
708 1780 if (is_singular() && $this->current_post_id) {
709 - if (has_post_thumbnail($this->current_post_id)) {
1781 + if (!empty($og_image_override)) {
1782 + $primary_og_image = (string) $og_image_override;
1783 + echo "<meta property=\"og:image\" content=\"" . esc_url($og_image_override) . "\" />\n";
1784 + echo "<meta property=\"og:image:secure_url\" content=\"" . esc_url($og_image_override) . "\" />\n";
1785 + } elseif (has_post_thumbnail($this->current_post_id)) {
710 1786 $image_url = get_the_post_thumbnail_url($this->current_post_id, 'large');
1787 + $primary_og_image = (string) $image_url;
711 1788 echo "<meta property=\"og:image\" content=\"" . esc_url($image_url) . "\" />\n";
712 1789 echo "<meta property=\"og:image:secure_url\" content=\"" . esc_url($image_url) . "\" />\n";
713 1790
714 1791 // Get image dimensions and alt text
@@ -714,11 +1791,22 @@
714 1791 // Get image dimensions and alt text
715 1792 $image_id = get_post_thumbnail_id($this->current_post_id);
716 1793 $image_meta = wp_get_attachment_metadata($image_id);
717 1794 if ($image_meta) {
718 - echo "<meta property=\"og:image:width\" content=\"" . esc_attr($image_meta['width']) . "\" />\n";
719 - echo "<meta property=\"og:image:height\" content=\"" . esc_attr($image_meta['height']) . "\" />\n";
720 - echo "<meta property=\"og:image:type\" content=\"image/jpeg\" />\n";
1795 + // SVGs (and other vector uploads) report 0x0 — emitting
1796 + // those as og:image dimensions is invalid, so skip them.
1797 + $og_width = isset($image_meta['width']) ? (int) $image_meta['width'] : 0;
1798 + $og_height = isset($image_meta['height']) ? (int) $image_meta['height'] : 0;
1799 + if ($og_width > 0 && $og_height > 0) {
1800 + echo "<meta property=\"og:image:width\" content=\"" . esc_attr($og_width) . "\" />\n";
1801 + echo "<meta property=\"og:image:height\" content=\"" . esc_attr($og_height) . "\" />\n";
1802 + }
1803 + // Derive the real mime type instead of hardcoding image/jpeg,
1804 + // which mislabels PNG/WebP featured images.
1805 + $image_mime = get_post_mime_type($image_id);
1806 + if ($image_mime) {
1807 + echo "<meta property=\"og:image:type\" content=\"" . esc_attr($image_mime) . "\" />\n";
1808 + }
721 1809 }
722 1810
723 1811 // Add image alt text
724 1812 $image_alt = get_post_meta($image_id, '_wp_attachment_image_alt', true);
@@ -726,8 +1814,30 @@
726 1814 echo "<meta property=\"og:image:alt\" content=\"" . esc_attr($image_alt) . "\" />\n";
727 1815 }
728 1816 }
729 1817
1818 + // Alternatives, same as the enhanced emitter above. This path only
1819 + // runs when the Social Meta Manager is unavailable, but the issue
1820 + // reported against it (#636) and a site that lands here should not
1821 + // silently lose a feature it switched on.
1822 + if (!empty($primary_og_image)) {
1823 + $social_settings = $this->social_manager
1824 + ? $this->social_manager->get_settings(
1825 + $this->current_context === 'homepage' ? 'site' : $this->current_context,
1826 + $this->current_post_id
1827 + )
1828 + : [];
1829 +
1830 + if (!empty($social_settings['og_multiple_images'])) {
1831 + self::output_extra_og_images(
1832 + \ThinkRank\SEO\Social_Images::additional(
1833 + (int) $this->current_post_id,
1834 + $primary_og_image
1835 + )
1836 + );
1837 + }
1838 + }
1839 +
730 1840 // Add article specific tags for posts only
731 1841 if ($og_type === 'article') {
732 1842 echo '<meta property="article:published_time" content="' . esc_attr(get_the_date('c', $this->current_post_id)) . '" />' . "\n";
733 1843 echo '<meta property="article:modified_time" content="' . esc_attr(get_the_modified_date('c', $this->current_post_id)) . '" />' . "\n";
@@ -747,9 +1857,9 @@
747 1857 }
748 1858 }
749 1859 echo "<!-- /ThinkRank SEO Open Graph Meta Tags -->\n";
750 1860 }
751 -
1861 +
752 1862 /**
753 1863 * Output Twitter Card meta tags (HIGH PRIORITY)
754 1864 * Uses Social Meta Manager with fallback to Site Identity templates
755 1865 *
@@ -755,27 +1865,48 @@
755 1865 *
756 1866 * @return void
757 1867 */
758 1868 public function output_twitter_card_tags(): void {
1869 + // Per-content-type Twitter card switch; see output_open_graph_tags().
1870 + if (!\ThinkRank\SEO\Content_Type_Settings::is_enabled_for_current(
1871 + \ThinkRank\SEO\Content_Type_Settings::FEATURE_TWITTER,
1872 + true
1873 + )) {
1874 + return;
1875 + }
1876 +
1877 + // Same reasoning as the Open Graph block: nothing on a 404 is shareable.
1878 + if ($this->current_context === '404') {
1879 + return;
1880 + }
1881 +
759 1882 // Priority 1: Try Social Meta Manager (Social Media tab settings)
760 1883 if ($this->social_manager) {
761 1884 // Map context for Social Meta Manager (homepage -> site for site-wide settings)
762 1885 $social_context = $this->current_context === 'homepage' ? 'site' : $this->current_context;
763 1886
1887 + // Twitter title/description derive from the same content data, so
1888 + // pass the effective SEO title and meta description as fallbacks to
1889 + // keep a cleared override in step with the document <title>/meta
1890 + // description and the metabox preview.
764 1891 $social_data = $this->social_manager->get_output_data(
765 1892 $social_context,
766 - $this->current_post_id
1893 + $this->current_post_id,
1894 + $this->get_effective_seo_title(),
1895 + $this->get_meta_description()
767 1896 );
768 1897
769 1898
770 -
771 - if ($social_data['enabled'] && !empty($social_data['twitter_tags'])) {
1899 + // The Social Meta Manager ran, so it owns Twitter output. If Twitter
1900 + // Cards are toggled off, emit nothing — do NOT fall through to the
1901 + // basic emitter (which would re-add twitter:* tags despite the toggle).
1902 + if (!empty($social_data['twitter_enabled'])) {
772 1903 $this->output_social_twitter_tags($social_data['twitter_tags']);
773 - return;
774 1904 }
1905 + return;
775 1906 }
776 1907
777 - // Priority 2: Fallback to current implementation
1908 + // Priority 2: Fallback only when the Social Meta Manager is unavailable.
778 1909 $this->output_basic_twitter_tags();
779 1910 }
780 1911
781 1912 /**
@@ -783,11 +1914,35 @@
783 1914 *
784 1915 * @return void
785 1916 */
786 1917 private function output_basic_twitter_tags(): void {
787 - // Get title using priority system: post-specific > Site Identity > default
1918 + // Check for per-post Twitter overrides first, then fall through to OG overrides.
1919 + $twitter_title_override = '';
1920 + $twitter_description_override = '';
1921 + $og_title_override = '';
1922 + $og_description_override = '';
1923 + if (is_singular() && $this->current_post_id) {
1924 + // Social fields may hold variable tags entered in the metabox.
1925 + $pid = $this->current_post_id;
1926 + $twitter_title_override = \ThinkRank\SEO\Pattern_Resolver::resolve_value((string) get_post_meta($pid, '_thinkrank_twitter_title', true), $pid);
1927 + $twitter_description_override = \ThinkRank\SEO\Pattern_Resolver::resolve_value((string) get_post_meta($pid, '_thinkrank_twitter_description', true), $pid);
1928 + $og_title_override = \ThinkRank\SEO\Pattern_Resolver::resolve_value((string) get_post_meta($pid, '_thinkrank_og_title', true), $pid);
1929 + $og_description_override = \ThinkRank\SEO\Pattern_Resolver::resolve_value((string) get_post_meta($pid, '_thinkrank_og_description', true), $pid);
1930 + } elseif ($this->current_term_id) {
1931 + $tid = $this->current_term_id;
1932 + $twitter_title_override = \ThinkRank\SEO\Pattern_Resolver::resolve_term_value((string) get_term_meta($tid, '_thinkrank_twitter_title', true), $tid);
1933 + $twitter_description_override = \ThinkRank\SEO\Pattern_Resolver::resolve_term_value((string) get_term_meta($tid, '_thinkrank_twitter_description', true), $tid);
1934 + $og_title_override = \ThinkRank\SEO\Pattern_Resolver::resolve_term_value((string) get_term_meta($tid, '_thinkrank_og_title', true), $tid);
1935 + $og_description_override = \ThinkRank\SEO\Pattern_Resolver::resolve_term_value((string) get_term_meta($tid, '_thinkrank_og_description', true), $tid);
1936 + }
1937 +
1938 + // Title cascade: Twitter override > OG override > Global SEO > Site Identity > default
788 1939 $title = '';
789 - if ($this->has_thinkrank_metadata() && !empty($this->current_metadata['title'])) {
1940 + if (!empty($twitter_title_override)) {
1941 + $title = $twitter_title_override;
1942 + } elseif (!empty($og_title_override)) {
1943 + $title = $og_title_override;
1944 + } elseif ($this->has_thinkrank_metadata() && !empty($this->current_metadata['title'])) {
790 1945 $title = $this->current_metadata['title'];
791 1946 } else {
792 1947 $title = $this->generate_context_title();
793 1948 }
@@ -794,12 +1949,24 @@
794 1949 if (!$title) {
795 1950 $title = is_singular() ? get_the_title() : get_bloginfo('name');
796 1951 }
797 1952
798 - $description = $this->get_meta_description();
799 - if (!$description) {
800 - $description = is_singular() ? wp_trim_words(get_the_excerpt(), 30) : get_bloginfo('description');
1953 + // Description cascade: Twitter override > OG override > meta description > excerpt
1954 + $description = '';
1955 + if (!empty($twitter_description_override)) {
1956 + $description = $twitter_description_override;
1957 + } elseif (!empty($og_description_override)) {
1958 + $description = $og_description_override;
1959 + } else {
1960 + $description = $this->get_meta_description();
801 1961 }
1962 + // Skipped for a protected post: core answers get_the_excerpt() with its
1963 + // "There is no excerpt because this is a protected post." placeholder,
1964 + // so this is not a leak — but publishing that sentence as the social
1965 + // description is worse than publishing none (#363).
1966 + if (!$description && !$this->is_content_password_protected()) {
1967 + $description = is_singular() ? \ThinkRank\Core\Seo_Text::trim_words(get_the_excerpt(), 30) : get_bloginfo('description');
1968 + }
802 1969
803 1970 // Determine card type based on image availability
804 1971 $card_type = 'summary';
805 1972 if (is_singular() && $this->current_post_id && has_post_thumbnail($this->current_post_id)) {
@@ -807,9 +1974,9 @@
807 1974 }
808 1975
809 1976 echo "<!-- ThinkRank SEO Twitter Card Meta Tags -->\n";
810 1977 echo '<meta name="twitter:card" content="' . esc_attr($card_type) . '" />' . "\n";
811 - echo "<meta name=\"twitter:title\" content=\"" . esc_attr($title) . "\" />\n";
1978 + echo "<meta name=\"twitter:title\" content=\"" . esc_attr(self::strip_title_tags($title)) . "\" />\n";
812 1979 echo "<meta name=\"twitter:description\" content=\"" . esc_attr($description) . "\" />\n";
813 1980
814 1981 // Add Twitter image with proper fallback priority
815 1982 $twitter_image_url = $this->get_twitter_image_with_fallback();
@@ -839,9 +2006,9 @@
839 2006 echo "<meta name=\"twitter:site\" content=\"" . esc_attr($twitter_handle) . "\" />\n";
840 2007 }
841 2008 echo "<!-- /ThinkRank SEO Twitter Card Meta Tags -->\n";
842 2009 }
843 -
2010 +
844 2011 /**
845 2012 * Output canonical URL
846 2013 *
847 2014 * @return void
@@ -846,30 +2013,290 @@
846 2013 *
847 2014 * @return void
848 2015 */
849 2016 public function output_canonical_url(): void {
850 - if (!is_singular()) {
2017 + $canonical_url = '';
2018 +
2019 + if (is_singular()) {
2020 + // Check for custom canonical URL override
2021 + if ($this->current_post_id) {
2022 + $custom_canonical = get_post_meta($this->current_post_id, '_thinkrank_canonical_url', true);
2023 + if (!empty($custom_canonical)) {
2024 + $canonical_url = $custom_canonical;
2025 + }
2026 + }
2027 +
2028 + if (empty($canonical_url)) {
2029 + $canonical_url = $this->current_post_id ? get_permalink($this->current_post_id) : get_permalink();
2030 +
2031 + // Core's rel_canonical() keeps the page number; this replaced
2032 + // it with a bare permalink, so every <!--nextpage--> sub-page
2033 + // and every /comment-page-N/ canonicalised to page 1 — a
2034 + // regression against core behaviour (#397). A custom canonical
2035 + // is left exactly as the user typed it.
2036 + $canonical_url = self::with_singular_page($canonical_url);
2037 + }
2038 + } else {
2039 + $canonical_url = self::get_non_singular_canonical_url();
2040 + }
2041 +
2042 + /**
2043 + * Filter the canonical URL before output.
2044 + *
2045 + * @since 1.16.0
2046 + *
2047 + * @param string $canonical_url Canonical URL ('' suppresses the tag).
2048 + */
2049 + $canonical_url = apply_filters('thinkrank_canonical_url', $canonical_url);
2050 +
2051 + if (empty($canonical_url)) {
851 2052 return;
852 2053 }
853 2054
854 - $canonical_url = $this->current_post_id ? get_permalink($this->current_post_id) : get_permalink();
2055 + // After the filter, so a canonical an add-on supplied is normalized
2056 + // too — and a cross-domain one is left alone, since Url_Scheme only
2057 + // touches URLs on this site's own host.
2058 + $canonical_url = \ThinkRank\SEO\Url_Scheme::apply($canonical_url);
2059 +
855 2060 echo "<!-- ThinkRank SEO Canonical URL -->\n";
856 2061 echo "<link rel=\"canonical\" href=\"" . esc_url($canonical_url) . "\" />\n";
857 2062 echo "<!-- /ThinkRank SEO Canonical URL -->\n";
2063 +
2064 + $this->output_pagination_links();
858 2065 }
859 -
860 2066
2067 + /**
2068 + * Emit rel="prev" / rel="next" on a paginated archive.
2069 + *
2070 + * Nothing emitted these at all (#397). Google stopped using them as an
2071 + * indexing signal in 2019, so this is not an SEO win with Google — Bing
2072 + * still reads them, and they are the standard way to describe a sequence,
2073 + * which is what the pages are.
2074 + *
2075 + * @since 2.0.1
2076 + *
2077 + * @return void
2078 + */
2079 + private function output_pagination_links(): void {
2080 + // Page 1 still wants a rel="next" when there is a page 2, so only
2081 + // singular views are skipped outright.
2082 + if (is_singular()) {
2083 + return;
2084 + }
861 2085
2086 + global $wp_query;
2087 +
2088 + $total = $wp_query ? (int) $wp_query->max_num_pages : 0;
2089 +
2090 + if ($total < 2) {
2091 + return;
2092 + }
2093 +
2094 + $base = self::get_non_singular_canonical_url();
2095 +
2096 + if ('' === $base) {
2097 + return;
2098 + }
2099 +
2100 + // get_non_singular_canonical_url() already carries the current page —
2101 + // strip it back to page 1 before building the neighbours.
2102 + $current = self::current_page_number();
2103 + $base = self::without_pagination($base);
2104 +
2105 + if ($current > 1) {
2106 + printf(
2107 + "<link rel=\"prev\" href=\"%s\" />\n",
2108 + esc_url(\ThinkRank\SEO\Url_Scheme::apply(self::with_pagination($base, $current - 1)))
2109 + );
2110 + }
2111 +
2112 + if ($current < $total) {
2113 + printf(
2114 + "<link rel=\"next\" href=\"%s\" />\n",
2115 + esc_url(\ThinkRank\SEO\Url_Scheme::apply(self::with_pagination($base, $current + 1)))
2116 + );
2117 + }
2118 + }
2119 +
862 2120 /**
2121 + * The rewrite base WordPress uses for page numbers ('page' by default).
2122 + *
2123 + * @since 2.0.1
2124 + *
2125 + * @return string
2126 + */
2127 + private static function pagination_base(): string {
2128 + global $wp_rewrite;
2129 +
2130 + return $wp_rewrite && $wp_rewrite->pagination_base ? $wp_rewrite->pagination_base : 'page';
2131 + }
2132 +
2133 + /**
2134 + * Append the sub-page or comment-page number to a singular canonical.
2135 + *
2136 + * @since 2.0.1
2137 + *
2138 + * @param string $url Permalink.
2139 + * @return string Permalink with the current page appended, when there is one.
2140 + */
2141 + public static function with_singular_page(string $url): string {
2142 + global $wp_rewrite;
2143 +
2144 + $page = (int) get_query_var('page');
2145 +
2146 + if ($page > 1) {
2147 + return $wp_rewrite && $wp_rewrite->using_permalinks()
2148 + ? trailingslashit($url) . user_trailingslashit($page, 'single_paged')
2149 + : add_query_arg('page', $page, $url);
2150 + }
2151 +
2152 + $comment_page = (int) get_query_var('cpage');
2153 +
2154 + if ($comment_page > 1) {
2155 + return get_comments_pagenum_link($comment_page);
2156 + }
2157 +
2158 + return $url;
2159 + }
2160 +
2161 + /**
2162 + * Build the canonical URL for non-singular contexts.
2163 + *
2164 + * Covers the blog home, post type / taxonomy / author / date archives.
2165 + * Search results and 404 pages get no canonical (they are noindexed).
2166 + * Paginated archives canonicalize to their own page URL so page 2+ is
2167 + * self-referential rather than pointing at page 1.
2168 + *
2169 + * @return string Canonical URL or '' when none applies
2170 + */
2171 + public static function get_non_singular_canonical_url(): string {
2172 + if (is_404() || is_search()) {
2173 + return '';
2174 + }
2175 +
2176 + $canonical_url = '';
2177 +
2178 + if (is_front_page() || is_home()) {
2179 + $canonical_url = is_home() && !is_front_page()
2180 + ? (string) get_permalink((int) get_option('page_for_posts'))
2181 + : home_url('/');
2182 + } elseif (is_post_type_archive()) {
2183 + $canonical_url = (string) get_post_type_archive_link((string) get_query_var('post_type'));
2184 + } elseif (is_category() || is_tag() || is_tax()) {
2185 + $term_link = get_term_link(get_queried_object());
2186 + $canonical_url = is_wp_error($term_link) ? '' : $term_link;
2187 + } elseif (is_author()) {
2188 + $canonical_url = get_author_posts_url((int) get_queried_object_id());
2189 + } elseif (is_date()) {
2190 + if (is_day()) {
2191 + $canonical_url = get_day_link((int) get_query_var('year'), (int) get_query_var('monthnum'), (int) get_query_var('day'));
2192 + } elseif (is_month()) {
2193 + $canonical_url = get_month_link((int) get_query_var('year'), (int) get_query_var('monthnum'));
2194 + } elseif (is_year()) {
2195 + $canonical_url = get_year_link((int) get_query_var('year'));
2196 + }
2197 + }
2198 +
2199 + if (empty($canonical_url)) {
2200 + return '';
2201 + }
2202 +
2203 + // Point paginated archives at their own page, not page 1.
2204 + return self::with_pagination($canonical_url, (int) get_query_var('paged'));
2205 + }
2206 +
2207 + /**
2208 + * Append a page number to a URL the way WordPress does.
2209 + *
2210 + * Extracted so the archive canonical is not the only thing that knows how
2211 + * to build a paged URL: the schema graph derived its @id from the
2212 + * un-paginated link, so every page of an archive claimed the same node
2213 + * identity, and the singular canonical dropped the page entirely (#397).
2214 + *
2215 + * @since 2.0.1
2216 + *
2217 + * @param string $url Base URL.
2218 + * @param int $page Page number; 1 or less returns the URL unchanged.
2219 + * @return string
2220 + */
2221 + public static function with_pagination(string $url, int $page): string {
2222 + if ($page <= 1 || '' === $url) {
2223 + return $url;
2224 + }
2225 +
2226 + global $wp_rewrite;
2227 +
2228 + if ($wp_rewrite && $wp_rewrite->using_permalinks()) {
2229 + return trailingslashit($url) . user_trailingslashit(
2230 + $wp_rewrite->pagination_base . '/' . $page,
2231 + 'paged'
2232 + );
2233 + }
2234 +
2235 + return add_query_arg('paged', $page, $url);
2236 + }
2237 +
2238 + /**
2239 + * Strip a page number from a URL, whichever form it takes.
2240 + *
2241 + * The inverse of with_pagination(). Pretty permalinks carry the page as a
2242 + * /page/N/ path segment, plain permalinks as a `paged` query arg, and a
2243 + * regex over the path alone silently left the latter in place — so
2244 + * rel="prev" on page 2 pointed at page 2 (#397 review).
2245 + *
2246 + * @since 2.0.1
2247 + *
2248 + * @param string $url URL that may carry a page number.
2249 + * @return string URL for page 1.
2250 + */
2251 + public static function without_pagination(string $url): string {
2252 + if ('' === $url) {
2253 + return $url;
2254 + }
2255 +
2256 + $url = remove_query_arg('paged', $url);
2257 +
2258 + return (string) preg_replace(
2259 + '#/' . preg_quote(self::pagination_base(), '#') . '/\d+/?$#',
2260 + '/',
2261 + $url
2262 + );
2263 + }
2264 +
2265 + /**
2266 + * The page number of the current request, archive or multi-page post.
2267 + *
2268 + * `paged` counts archive pages; `page` counts the <!--nextpage--> parts of
2269 + * a single post. They are never both set.
2270 + *
2271 + * @since 2.0.1
2272 + *
2273 + * @return int Page number, 1 when this is the first page.
2274 + */
2275 + public static function current_page_number(): int {
2276 + $paged = (int) get_query_var('paged');
2277 +
2278 + if ($paged > 1) {
2279 + return $paged;
2280 + }
2281 +
2282 + $page = (int) get_query_var('page');
2283 +
2284 + return $page > 1 ? $page : 1;
2285 + }
2286 +
2287 +
2288 + /**
863 2289 * Check if ThinkRank has metadata for current post
864 2290 *
865 2291 * @return bool True if has ThinkRank metadata
866 2292 */
867 2293 private function has_thinkrank_metadata(): bool {
868 - if (!is_singular()) {
869 - return false;
870 - }
871 -
2294 + // Populated by initialize_current_context() for singular views and for
2295 + // term archives, and left empty everywhere else — so the emptiness
2296 + // check is the whole test. The `!is_singular()` early return this
2297 + // replaced is what made every stored term title and description inert:
2298 + // the entire title/description cascade hangs off this method (#386).
872 2299 return !empty($this->current_metadata['title']) || !empty($this->current_metadata['description']);
873 2300 }
874 2301
875 2302 /**
@@ -904,9 +2331,9 @@
904 2331 }
905 2332
906 2333 return $this->generate_breadcrumbs($settings);
907 2334 }
908 -
2335 +
909 2336 /**
910 2337 * Get current SEO metadata
911 2338 *
912 2339 * @return array Current metadata
@@ -920,8 +2347,15 @@
920 2347 *
921 2348 * @return string|null Generated title or null if no template available
922 2349 */
923 2350 private function generate_context_title(): ?string {
2351 + // Priority 1: Try Global SEO settings for current post type
2352 + $global_seo_title = $this->get_global_seo_title();
2353 + if ($global_seo_title) {
2354 + return $global_seo_title;
2355 + }
2356 +
2357 + // Priority 2: Fall back to Site Identity templates
924 2358 if (!$this->site_identity_data || !$this->site_identity_data['enabled']) {
925 2359 return null;
926 2360 }
927 2361
@@ -934,8 +2368,135 @@
934 2368 return $this->process_title_template($template, $placeholders);
935 2369 }
936 2370
937 2371 /**
2372 + * Get title from Global SEO settings for current post type
2373 + *
2374 + * @return string|null Generated title or null if no Global SEO template available
2375 + */
2376 + private function get_global_seo_title(): ?string {
2377 + // Only apply Global SEO to singular posts/pages
2378 + if (!is_singular()) {
2379 + return null;
2380 + }
2381 +
2382 + $post_type = get_post_type();
2383 + if (!$post_type) {
2384 + return null;
2385 + }
2386 +
2387 + // Get Global SEO settings for this post type
2388 + $global_seo_settings = $this->get_global_seo_settings($post_type);
2389 + if (empty($global_seo_settings['title'])) {
2390 + return null;
2391 + }
2392 +
2393 + $template = $global_seo_settings['title'];
2394 + $placeholders = $this->get_global_seo_placeholders();
2395 +
2396 + return $this->process_global_seo_template($template, $placeholders);
2397 + }
2398 +
2399 + /**
2400 + * Get Global SEO settings for a post type
2401 + *
2402 + * @param string $post_type Post type slug
2403 + * @return array Global SEO settings or empty array
2404 + */
2405 + private function get_global_seo_settings(string $post_type): array {
2406 + $all_settings = get_option('thinkrank_global_seo_settings', []);
2407 + return $all_settings[$post_type] ?? [];
2408 + }
2409 +
2410 + /**
2411 + * Get placeholders for Global SEO template processing
2412 + *
2413 + * @return array Placeholder values
2414 + */
2415 + private function get_global_seo_placeholders(): array {
2416 + $placeholders = [
2417 + '%title%' => '',
2418 + '%sitename%' => get_bloginfo('name'),
2419 + '%sep%' => $this->get_global_seo_separator(),
2420 + '%excerpt%' => '',
2421 + '%date%' => get_the_date(),
2422 + '%modified%' => get_the_modified_date(),
2423 + '%author%' => '',
2424 + '%category%' => '',
2425 + ];
2426 +
2427 + // Get current post data if available
2428 + if ($this->current_post_id) {
2429 + $placeholders['%title%'] = get_the_title($this->current_post_id);
2430 +
2431 + // Get excerpt
2432 + $post = get_post($this->current_post_id);
2433 + if ($post) {
2434 + // An authored post_excerpt is written for public consumption, so
2435 + // it stays. Falling back to the body does not: for a protected
2436 + // post that derivation leaks the gated content through any
2437 + // template containing %excerpt%, and this branch runs BEFORE the
2438 + // derive-from-content priority below, so guarding only that one
2439 + // would leave this path open (#363).
2440 + if (!empty($post->post_excerpt)) {
2441 + $placeholders['%excerpt%'] = $post->post_excerpt;
2442 + } elseif (!$this->is_content_password_protected($post->ID)) {
2443 + $placeholders['%excerpt%'] = \ThinkRank\SEO\Pattern_Resolver::derive_excerpt(
2444 + \ThinkRank\SEO\Builder_Content::visible_content($post)
2445 + );
2446 + }
2447 + }
2448 +
2449 + // Get author
2450 + $author_id = get_post_field('post_author', $this->current_post_id);
2451 + $placeholders['%author%'] = get_the_author_meta('display_name', $author_id);
2452 +
2453 + // Get category (for posts)
2454 + if (get_post_type($this->current_post_id) === 'post') {
2455 + $categories = get_the_category($this->current_post_id);
2456 + $placeholders['%category%'] = !empty($categories) ? $categories[0]->name : '';
2457 + }
2458 + }
2459 +
2460 + return $placeholders;
2461 + }
2462 +
2463 + /**
2464 + * Get separator for Global SEO title
2465 + *
2466 + * @return string Separator symbol
2467 + */
2468 + public function get_global_seo_separator(): string {
2469 + return \ThinkRank\SEO\Site_Identity_Manager::get_active_separator_symbol();
2470 + }
2471 +
2472 + /**
2473 + * Process Global SEO template with placeholders
2474 + *
2475 + * @param string $template Template string with variables
2476 + * @param array $placeholders Placeholder values
2477 + * @return string Processed title
2478 + */
2479 + private function process_global_seo_template(string $template, array $placeholders): string {
2480 + // Replace all placeholders
2481 + $title = str_replace(array_keys($placeholders), array_values($placeholders), $template);
2482 +
2483 + // Clean up multiple spaces
2484 + $title = preg_replace('/\s+/', ' ', $title);
2485 + $title = trim($title);
2486 +
2487 + // Clean up multiple separators (e.g., "| |" becomes "|")
2488 + $separator = $placeholders['%sep%'] ?? '|';
2489 + $separator_pattern = preg_quote($separator, '/');
2490 + $title = preg_replace('/\s*' . $separator_pattern . '\s*' . $separator_pattern . '\s*/', ' ' . $separator . ' ', $title);
2491 +
2492 + // Remove leading/trailing separators
2493 + $title = trim($title, " \t\n\r\0\x0B" . $separator);
2494 +
2495 + return $title;
2496 + }
2497 +
2498 + /**
938 2499 * Get title template for current context
939 2500 *
940 2501 * @return string|null Template string or null if not found
941 2502 */
@@ -943,8 +2504,17 @@
943 2504 $settings = $this->site_identity_manager->get_settings('site');
944 2505
945 2506 switch ($this->current_context) {
946 2507 case 'homepage':
2508 + // detect_current_context() collapses the static posts page into
2509 + // 'homepage', so it rendered the front page's title template and
2510 + // the two pages shipped the same <title> — a duplicate title on
2511 + // the site's two most-linked URLs (#397 review). It is a page,
2512 + // and it has its own name, so it gets the page template.
2513 + if (self::is_static_posts_page()) {
2514 + return $settings['page_title'] ?? $settings['homepage_title'] ?? null;
2515 + }
2516 +
947 2517 return $settings['homepage_title'] ?? null;
948 2518 case 'post':
949 2519 return $settings['post_title'] ?? null;
950 2520 case 'page':
@@ -975,13 +2545,20 @@
975 2545 $settings = $this->site_identity_manager->get_settings('site');
976 2546 $separator = $this->get_title_separator($settings['title_separator'] ?? 'pipe');
977 2547
978 2548 $placeholders = [
979 - '%site_title%' => $settings['site_name'] ?? get_bloginfo('name'),
980 - '%site_name%' => $settings['site_name'] ?? get_bloginfo('name'),
981 - '%site_description%' => $settings['site_description'] ?? get_bloginfo('description'),
982 - '%tagline%' => $settings['tagline'] ?? get_bloginfo('description'),
2549 + // first_non_empty(), not `??`: Site Identity persists these as ''
2550 + // rather than leaving them unset, and '' is not null — so the
2551 + // null-coalesce stopped dead on the empty string and the WordPress
2552 + // fallback was unreachable. A site with a tagline set in Settings →
2553 + // General rendered "%site_description%" as nothing (#398). This is
2554 + // the same reasoning first_non_empty()'s own docblock records.
2555 + '%site_title%' => $this->first_non_empty($settings['site_name'] ?? '', get_bloginfo('name')),
2556 + '%site_name%' => $this->first_non_empty($settings['site_name'] ?? '', get_bloginfo('name')),
2557 + '%site_description%' => $this->first_non_empty($settings['site_description'] ?? '', get_bloginfo('description')),
2558 + '%tagline%' => $this->first_non_empty($settings['tagline'] ?? '', get_bloginfo('description')),
983 2559 '%separator%' => ' ' . $separator . ' ',
2560 + '%sep%' => ' ' . $separator . ' ',
984 2561 '%date%' => gmdate('F Y'),
985 2562 ];
986 2563
987 2564 // Context-specific placeholders
@@ -1032,10 +2609,26 @@
1032 2609 $placeholders['%search_term%'] = get_search_query();
1033 2610 break;
1034 2611
1035 2612 case 'archive':
1036 - $placeholders['%archive_title%'] = get_the_archive_title();
2613 + // Stripped: get_the_archive_title() wraps its subject in a
2614 + // <span>, and this placeholder feeds the document <title> as
2615 + // well as og:title and twitter:title — a date archive rendered
2616 + // as "Month: <span>August 2026</span> | Site".
2617 + $placeholders['%archive_title%'] = self::archive_subject();
1037 2618 break;
2619 +
2620 + case 'homepage':
2621 + // The page template resolved for a static posts page needs the
2622 + // page's own name; without it %title%/%page_title% would render
2623 + // empty and collapse back to the site title.
2624 + if (self::is_static_posts_page()) {
2625 + $posts_page_title = get_the_title((int) get_option('page_for_posts'));
2626 + $placeholders['%title%'] = $posts_page_title;
2627 + $placeholders['%page_title%'] = $posts_page_title;
2628 + $placeholders['%post_title%'] = $posts_page_title;
2629 + }
2630 + break;
1038 2631 }
1039 2632
1040 2633 return $placeholders;
1041 2634 }
@@ -1040,8 +2633,19 @@
1040 2633 return $placeholders;
1041 2634 }
1042 2635
1043 2636 /**
2637 + * Whether this request is a static posts page rather than the front page.
2638 + *
2639 + * @since 2.0.1
2640 + *
2641 + * @return bool
2642 + */
2643 + private static function is_static_posts_page(): bool {
2644 + return is_home() && !is_front_page() && (int) get_option('page_for_posts') > 0;
2645 + }
2646 +
2647 + /**
1044 2648 * Process title template with placeholders
1045 2649 *
1046 2650 * @param string $template Template string
1047 2651 * @param array $placeholders Placeholder values
@@ -1051,8 +2655,11 @@
1051 2655 $title = str_replace(array_keys($placeholders), array_values($placeholders), $template);
1052 2656
1053 2657 // Clean up multiple separators and extra spaces
1054 2658 $separator = $placeholders['%separator%'] ?? ' | ';
2659 +
2660 + // Legacy templates stored a literal pipe as separator — apply the active separator to them
2661 + $title = preg_replace('/\s*\|\s*/', $separator, $title);
1055 2662 $title = preg_replace('/\s*' . preg_quote(trim($separator), '/') . '\s*' . preg_quote(trim($separator), '/') . '\s*/', $separator, $title);
1056 2663 $title = preg_replace('/\s+/', ' ', $title);
1057 2664 $title = trim($title);
1058 2665
@@ -1071,26 +2678,48 @@
1071 2678 * @param string $separator_type Separator type
1072 2679 * @return string Separator symbol
1073 2680 */
1074 2681 private function get_title_separator(string $separator_type): string {
1075 - $separators = [
1076 - 'pipe' => '|',
1077 - 'dash' => '-',
1078 - 'ndash' => '–',
1079 - 'mdash' => '—',
1080 - 'middot' => '·',
1081 - 'bull' => '•',
1082 - 'star' => '*',
1083 - 'smstar' => '⋆',
1084 - 'gt' => '>',
1085 - 'raquo' => '»',
1086 - ];
2682 + return \ThinkRank\SEO\Site_Identity_Manager::$title_separators[$separator_type]['symbol'] ?? \ThinkRank\SEO\Site_Identity_Manager::$title_separators['pipe']['symbol'];
2683 + }
1087 2684
1088 - return $separators[$separator_type] ?? '|';
2685 + /**
2686 + * Whether a post's body must not be read for a public surface.
2687 + *
2688 + * Deriving metadata from `post_content` publishes that content to everyone
2689 + * who requests the URL — and to every crawler and link-preview unfurler
2690 + * that reads og:description — while the page itself still shows only the
2691 + * password form, so the leak is invisible to the site owner (#363).
2692 + *
2693 + * This is the one thing every content reader should call before touching
2694 + * `post_content` for output. It mirrors core: a visitor who has already
2695 + * entered the correct password sees the body anyway, so nothing is hidden
2696 + * from them here either.
2697 + *
2698 + * @param int|null $post_id Optional. Post ID. Defaults to the current post.
2699 + * @return bool True when the body is password-gated for this visitor.
2700 + */
2701 + private function is_content_password_protected(?int $post_id = null): bool {
2702 + $post_id = $post_id ?? $this->current_post_id;
2703 +
2704 + if (!$post_id) {
2705 + return false;
2706 + }
2707 +
2708 + $post = get_post($post_id);
2709 +
2710 + if (!$post) {
2711 + return false;
2712 + }
2713 +
2714 + // Guarded for the same reason the schema path guards it: this class is
2715 + // also exercised outside a full front-end request.
2716 + return function_exists('post_password_required') && post_password_required($post);
1089 2717 }
1090 2718
1091 2719 /**
1092 2720 * Get meta description with fallback system
2721 + * Priority: Post-specific metadata > Global SEO templates > Site Identity templates > WordPress defaults
1093 2722 *
1094 2723 * @return string|null Meta description or null if none available
1095 2724 */
1096 2725 private function get_meta_description(): ?string {
@@ -1098,9 +2727,22 @@
1098 2727 if ($this->has_thinkrank_metadata() && !empty($this->current_metadata['description'])) {
1099 2728 return $this->current_metadata['description'];
1100 2729 }
1101 2730
1102 - // Second priority: Site Identity default meta description
2731 + // Second priority: Global SEO description template
2732 + $global_seo_description = $this->get_global_seo_description();
2733 + if ($global_seo_description) {
2734 + return $global_seo_description;
2735 + }
2736 +
2737 + // Archive contexts: derive the description from the archive itself
2738 + // (term description, post type description, author bio)
2739 + $archive_description = $this->get_archive_meta_description();
2740 + if ($archive_description) {
2741 + return $archive_description;
2742 + }
2743 +
2744 + // Third priority: Site Identity default meta description
1103 2745 if ($this->site_identity_data && $this->site_identity_data['enabled']) {
1104 2746 $settings = $this->site_identity_manager->get_settings('site');
1105 2747 $default_description = $settings['default_meta_description'] ?? '';
1106 2748
@@ -1108,13 +2750,23 @@
1108 2750 return $default_description;
1109 2751 }
1110 2752 }
1111 2753
1112 - // Third priority: Generate from content for posts/pages
1113 - if (is_singular() && $this->current_post_id) {
1114 - $post_content = get_post_field('post_content', $this->current_post_id);
2754 + // Fourth priority: Generate from content for posts/pages.
2755 + // Never for a password-protected post — deriving the description from a
2756 + // gated body published its first ~25 words in the page head, and the
2757 + // same value is reused for og:description and twitter:description, so
2758 + // one unguarded read leaked through three tags (#363).
2759 + if (is_singular() && $this->current_post_id && !$this->is_content_password_protected()) {
2760 + // Not the raw column: a Bricks page discards `post_content`, so
2761 + // whatever is still stored there is invisible — and this one value
2762 + // becomes the meta, og: and twitter: descriptions (#651).
2763 + $described = get_post($this->current_post_id);
2764 + $post_content = $described instanceof \WP_Post
2765 + ? \ThinkRank\SEO\Builder_Content::visible_content($described)
2766 + : get_post_field('post_content', $this->current_post_id);
1115 2767 if ($post_content) {
1116 - $excerpt = wp_trim_words(wp_strip_all_tags($post_content), 25, '...');
2768 + $excerpt = \ThinkRank\SEO\Pattern_Resolver::derive_excerpt((string) $post_content);
1117 2769 if (!empty($excerpt)) {
1118 2770 return $excerpt;
1119 2771 }
1120 2772 }
@@ -1119,9 +2771,9 @@
1119 2771 }
1120 2772 }
1121 2773 }
1122 2774
1123 - // Fourth priority: Site description for homepage
2775 + // Fifth priority: Site description for homepage
1124 2776 if (is_home() || is_front_page()) {
1125 2777 $site_description = get_bloginfo('description');
1126 2778 if (!empty($site_description)) {
1127 2779 return $site_description;
@@ -1131,8 +2783,98 @@
1131 2783 return null;
1132 2784 }
1133 2785
1134 2786 /**
2787 + * Get a meta description for archive contexts.
2788 + *
2789 + * Post type archives use the post type's description, taxonomy archives
2790 + * the term description, author archives the author bio. Returns null for
2791 + * non-archive contexts so the regular fallback chain continues.
2792 + *
2793 + * @return string|null Archive description or null when not applicable
2794 + */
2795 + private function get_archive_meta_description(): ?string {
2796 + $description = '';
2797 +
2798 + // Author archives are intentionally excluded — Author_Archives_Manager
2799 + // outputs its own template-based meta description on wp_head.
2800 + if (is_post_type_archive()) {
2801 + $post_type_object = get_queried_object();
2802 + if ($post_type_object instanceof \WP_Post_Type && !empty($post_type_object->description)) {
2803 + $description = $post_type_object->description;
2804 + }
2805 + } elseif (is_category() || is_tag() || is_tax()) {
2806 + $description = term_description() ?: '';
2807 + }
2808 +
2809 + $description = trim(wp_strip_all_tags((string) $description));
2810 + if ($description === '') {
2811 + return null;
2812 + }
2813 +
2814 + // Measure and cut in CHARACTERS. strlen() counts bytes, so a Thai or
2815 + // CJK description tripped this limit at a third of its length, and
2816 + // wp_trim_words() then cut by a unit the locale chooses — 25 words in
2817 + // English, 25 characters in Thai (#687).
2818 + $description = \ThinkRank\Core\Seo_Text::trim_to_length($description);
2819 +
2820 + return $description;
2821 + }
2822 +
2823 + /**
2824 + * Get description from Global SEO settings for current post type
2825 + *
2826 + * @return string|null Generated description or null if no Global SEO template available
2827 + */
2828 + private function get_global_seo_description(): ?string {
2829 + // Only apply Global SEO to singular posts/pages
2830 + if (!is_singular()) {
2831 + return null;
2832 + }
2833 +
2834 + $post_type = get_post_type();
2835 + if (!$post_type) {
2836 + return null;
2837 + }
2838 +
2839 + // Get Global SEO settings for this post type
2840 + $global_seo_settings = $this->get_global_seo_settings($post_type);
2841 + if (empty($global_seo_settings['description'])) {
2842 + return null;
2843 + }
2844 +
2845 + $template = $global_seo_settings['description'];
2846 + $placeholders = $this->get_global_seo_placeholders();
2847 +
2848 + return $this->process_global_seo_description_template($template, $placeholders);
2849 + }
2850 +
2851 + /**
2852 + * Process Global SEO description template with placeholders
2853 + *
2854 + * @param string $template Template string with variables
2855 + * @param array $placeholders Placeholder values
2856 + * @return string Processed description
2857 + */
2858 + private function process_global_seo_description_template(string $template, array $placeholders): string {
2859 + // Replace all placeholders
2860 + $description = str_replace(array_keys($placeholders), array_values($placeholders), $template);
2861 +
2862 + // Clean up multiple spaces
2863 + $description = preg_replace('/\s+/', ' ', $description);
2864 + $description = trim($description);
2865 +
2866 + // Ensure description doesn't exceed recommended length (160 characters)
2867 + // Measure and cut in CHARACTERS. strlen() counts bytes, so a Thai or
2868 + // CJK description tripped this limit at a third of its length, and
2869 + // wp_trim_words() then cut by a unit the locale chooses — 25 words in
2870 + // English, 25 characters in Thai (#687).
2871 + $description = \ThinkRank\Core\Seo_Text::trim_to_length($description);
2872 +
2873 + return $description;
2874 + }
2875 +
2876 + /**
1135 2877 * Output site-wide schema markup with priority system
1136 2878 *
1137 2879 * Priority: Schema Manager > Site Identity (like Twitter Cards approach)
1138 2880 *
@@ -1139,9 +2881,21 @@
1139 2881 * @return void
1140 2882 */
1141 2883 public function output_site_schema_markup(): void {
1142 2884 $has_schema_manager_output = false;
2885 + $has_website_schema = false;
1143 2886
2887 + // The master switch on Essential SEO -> Schema Manager. Until #461 this
2888 + // was never read here, so turning schema off left every deployed entity
2889 + // on the page. Read it once and bail before touching the graph.
2890 + if ($this->schema_manager) {
2891 + $schema_settings = $this->schema_manager->get_settings('site', null);
2892 +
2893 + if (isset($schema_settings['enabled']) && !$schema_settings['enabled']) {
2894 + return;
2895 + }
2896 + }
2897 +
1144 2898 // PRIORITY 1: Always output site-wide schemas (Organization, Website, LocalBusiness, Person)
1145 2899 if ($this->schema_manager) {
1146 2900 $site_wide_schemas = $this->schema_manager->get_deployed_schemas('site', null);
1147 2901
@@ -1146,29 +2900,79 @@
1146 2900 $site_wide_schemas = $this->schema_manager->get_deployed_schemas('site', null);
1147 2901
1148 2902 if (!empty($site_wide_schemas)) {
1149 2903 foreach ($site_wide_schemas as $schema_type => $schema_info) {
1150 - $this->output_schema_markup($schema_info['data'], $schema_type, 'Schema Manager');
2904 + Schema_Graph::instance()->add_supporting($schema_info['data'], (string) $schema_type);
1151 2905 }
1152 2906 $has_schema_manager_output = true;
2907 + $has_website_schema = isset($site_wide_schemas['WebSite']);
1153 2908 }
1154 2909 }
1155 2910
2911 + // The homepage always gets a WebSite schema (with a SearchAction) so
2912 + // search engines can associate the site name and sitelinks searchbox —
2913 + // unless the Schema Manager already deployed one.
2914 + if ((is_front_page() || is_home()) && !$has_website_schema) {
2915 + $website_schema = $this->generate_website_schema();
2916 +
2917 + /**
2918 + * Filter the default homepage WebSite schema before output.
2919 + *
2920 + * @since 1.16.0
2921 + *
2922 + * @param array $website_schema WebSite schema array ([] suppresses output).
2923 + */
2924 + $website_schema = apply_filters('thinkrank_website_schema', $website_schema);
2925 +
2926 + if (!empty($website_schema)) {
2927 + Schema_Graph::instance()->add_supporting($website_schema, 'WebSite');
2928 + }
2929 + }
2930 +
1156 2931 // PRIORITY 2: Also output page-specific schemas (Article, HowTo, FAQ, etc.) on individual posts/pages
1157 2932 if ($this->schema_manager && (is_single() || is_page())) {
1158 - $context_type = is_page() ? 'page' : 'post';
1159 - $context_id = get_the_ID();
2933 + $context_id = get_the_ID();
2934 + $context_type = get_post_type( $context_id );
2935 + $context_type = in_array( $context_type, [ 'site', 'post', 'page', 'product' ] , true) ? $context_type : 'post';
1160 2936
1161 2937 $page_specific_schemas = $this->schema_manager->get_deployed_schemas($context_type, $context_id);
1162 2938
1163 2939 if (!empty($page_specific_schemas)) {
2940 + // Every deployed schema is rendered, on every plan. How many a
2941 + // page carries is decided when schemas are activated in the
2942 + // editor, not trimmed here by plan (#673).
2943 +
2944 + /**
2945 + * Filter the page-specific schemas rendered on the current page.
2946 + *
2947 + * @param array $page_specific_schemas Deployed schemas keyed by schema type.
2948 + * @param string $context_type Context type (post, page, product, site).
2949 + * @param int $context_id Post ID.
2950 + */
2951 + $page_specific_schemas = apply_filters(
2952 + 'thinkrank_page_schemas_to_render',
2953 + $page_specific_schemas,
2954 + $context_type,
2955 + $context_id
2956 + );
2957 +
1164 2958 foreach ($page_specific_schemas as $schema_type => $schema_info) {
1165 - $this->output_schema_markup($schema_info['data'], $schema_type, 'Schema Manager');
2959 + Schema_Graph::instance()->add_primary($schema_info['data'], (string) $schema_type, 'schema_manager');
1166 2960 }
1167 2961 $has_schema_manager_output = true;
1168 2962 }
1169 2963 }
1170 2964
2965 + // Absorb FAQ content from the post body (FAQ block / Elementor widget)
2966 + // so it merges into the graph's single FAQPage instead of each producer
2967 + // emitting its own competing one.
2968 + if (is_singular()) {
2969 + $queried_post = get_post();
2970 + if ($queried_post instanceof \WP_Post) {
2971 + Schema_Graph::instance()->collect_post_faq($queried_post);
2972 + }
2973 + }
2974 +
1171 2975 // Skip Site Identity fallback if any Schema Manager schemas were output
1172 2976 if ($has_schema_manager_output) {
1173 2977 return;
1174 2978 }
@@ -1187,67 +2991,140 @@
1187 2991
1188 2992 $schema = $this->generate_organization_schema($settings);
1189 2993
1190 2994 if ($schema) {
1191 - $this->output_schema_markup($schema, 'Organization', 'Site Identity');
2995 + Schema_Graph::instance()->add_supporting($schema, 'Organization');
1192 2996 }
1193 2997 }
1194 2998
1195 2999 /**
1196 - * Output schema markup with consistent formatting
3000 + * Generate the default WebSite schema for the homepage.
1197 3001 *
1198 - * @param array $schema_data Schema data
1199 - * @param string $schema_type Schema type name
1200 - * @param string $source Source of schema (Schema Manager, Site Identity, etc.)
1201 - * @return void
3002 + * Includes a SearchAction potentialAction so search engines can surface a
3003 + * sitelinks searchbox, mirroring what Rank Math/Yoast output by default.
3004 + *
3005 + * @return array WebSite schema
1202 3006 */
1203 - private function output_schema_markup(array $schema_data, string $schema_type, string $source): void {
1204 - if (empty($schema_data)) {
1205 - return;
3007 + private function generate_website_schema(): array {
3008 + $settings = $this->site_identity_manager ? $this->site_identity_manager->get_settings('site') : [];
3009 +
3010 + $schema = [
3011 + '@context' => 'https://schema.org',
3012 + '@type' => 'WebSite',
3013 + '@id' => home_url('/#website'),
3014 + 'name' => !empty($settings['site_name']) ? $settings['site_name'] : get_bloginfo('name'),
3015 + 'url' => home_url('/'),
3016 + ];
3017 +
3018 + $description = !empty($settings['site_description']) ? $settings['site_description'] : get_bloginfo('description');
3019 + if (!empty($description)) {
3020 + $schema['description'] = $description;
1206 3021 }
1207 3022
1208 - echo '<!-- ThinkRank ' . esc_html($source) . ': ' . esc_html($schema_type) . ' Schema -->' . "\n";
1209 - echo '<script type="application/ld+json">' . "\n";
1210 - echo wp_json_encode($schema_data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n";
1211 - echo '</script>' . "\n";
1212 - echo '<!-- /ThinkRank ' . esc_html($source) . ': ' . esc_html($schema_type) . ' Schema -->' . "\n";
3023 + // Site Identity has accepted an alternate name since the setup wizard
3024 + // shipped, and the MCP ability describes it as "published as schema
3025 + // alternateName" — but no producer ever read it, so the promise was
3026 + // false and every imported Yoast/Rank Math value sat unused (#692).
3027 + $alternate_name = \ThinkRank\SEO\Site_Identity_Manager::alternate_name_for_schema($settings['alternate_name'] ?? null);
3028 + if (null !== $alternate_name) {
3029 + $schema['alternateName'] = $alternate_name;
3030 + }
3031 +
3032 + // The sitelinks searchbox switch was honoured only for a deployed
3033 + // WebSite row; this live fallback added potentialAction unconditionally,
3034 + // so website_enable_search = 0 still shipped the SearchAction (#688).
3035 + // Absent means not configured, which stays enabled.
3036 + $search_enabled = true;
3037 + if ($this->schema_manager) {
3038 + $schema_settings = $this->schema_manager->get_settings('site', null);
3039 +
3040 + if (array_key_exists('website_enable_search', $schema_settings)) {
3041 + $search_enabled = !empty($schema_settings['website_enable_search']);
3042 + }
3043 + }
3044 +
3045 + if ($search_enabled) {
3046 + $schema['potentialAction'] = [
3047 + '@type' => 'SearchAction',
3048 + 'target' => [
3049 + '@type' => 'EntryPoint',
3050 + 'urlTemplate' => home_url('/?s={search_term_string}'),
3051 + ],
3052 + 'query-input' => 'required name=search_term_string',
3053 + ];
3054 + }
3055 +
3056 + return $schema;
1213 3057 }
1214 3058
1215 3059 /**
1216 3060 * Generate organization schema markup
1217 3061 *
1218 - * @param array $settings Site identity settings
3062 + * Priority: Schema Manager organization settings > Site Identity settings
3063 + *
3064 + * @param array $settings Site identity settings (used as fallback)
1219 3065 * @return array|null Schema data or null if insufficient data
1220 3066 */
1221 3067 private function generate_organization_schema(array $settings): ?array {
1222 - $site_name = $settings['site_name'] ?? get_bloginfo('name');
1223 - $site_description = $settings['site_description'] ?? get_bloginfo('description');
3068 + // PRIORITY 1: Get Schema Manager organization settings
3069 + $schema_settings = [];
3070 + if ($this->schema_manager) {
3071 + $schema_settings = $this->schema_manager->get_settings('site', null);
3072 + }
1224 3073
1225 - if (empty($site_name)) {
3074 + // Determine organization values (Schema Manager > Site Identity > WordPress default).
3075 + // Use first_non_empty() rather than ??: these settings keys are always present
3076 + // and default to an empty string, so a ?? chain would stop dead on '' and never
3077 + // reach the WordPress fallback.
3078 + $org_name = $this->first_non_empty(
3079 + $schema_settings['organization_name'] ?? null,
3080 + $settings['site_name'] ?? null,
3081 + get_bloginfo('name')
3082 + );
3083 +
3084 + $org_url = $this->first_non_empty(
3085 + $schema_settings['organization_url'] ?? null,
3086 + $settings['site_url'] ?? null,
3087 + home_url()
3088 + );
3089 +
3090 + $org_description = $this->first_non_empty(
3091 + $schema_settings['organization_description'] ?? null,
3092 + $settings['site_description'] ?? null,
3093 + get_bloginfo('description')
3094 + );
3095 +
3096 + if (empty($org_name)) {
1226 3097 return null;
1227 3098 }
1228 3099
3100 + // Determine organization type (Schema Manager setting or default)
3101 + $org_type = $schema_settings['organization_type'] ?? 'Organization';
3102 +
1229 3103 $schema = [
1230 3104 '@context' => 'https://schema.org',
1231 - '@type' => 'Organization',
3105 + '@type' => $org_type,
1232 3106 '@id' => home_url() . '#organization',
1233 - 'name' => $site_name,
1234 - 'url' => home_url(),
3107 + 'name' => $org_name,
3108 + 'url' => $org_url,
1235 3109 ];
1236 3110
1237 3111 // Add description if available
1238 - if (!empty($site_description)) {
1239 - $schema['description'] = $site_description;
3112 + if (!empty($org_description)) {
3113 + $schema['description'] = $org_description;
1240 3114 }
1241 3115
1242 3116 // Add logo if available with proper ImageObject structure
1243 - if (!empty($settings['logo_url'])) {
3117 + // Priority: Schema Manager logo > Site Identity logo
3118 + $logo_url = $schema_settings['organization_logo'] ?? $settings['logo_url'] ?? '';
3119 +
3120 + if (!empty($logo_url)) {
1244 3121 $schema['logo'] = [
1245 3122 '@type' => 'ImageObject',
1246 3123 '@id' => home_url() . '#logo',
1247 - 'url' => $settings['logo_url'],
1248 - 'contentUrl' => $settings['logo_url'],
1249 - 'caption' => $site_name . ' Logo'
3124 + 'url' => $logo_url,
3125 + 'contentUrl' => $logo_url,
3126 + 'caption' => $org_name . ' Logo'
1250 3127 ];
1251 3128
1252 3129 // Also add as image property
1253 3130 $schema['image'] = $schema['logo'];
@@ -1253,10 +3130,44 @@
1253 3130 $schema['image'] = $schema['logo'];
1254 3131 }
1255 3132
1256 3133 // Add social media accounts if available
3134 + // Priority: Schema Manager social profiles > Site Identity social profiles
1257 3135 $social_urls = [];
1258 - if (!empty($this->site_identity_data['social'])) {
3136 +
3137 + // Check Schema Manager organization social profiles first
3138 + if (!empty($schema_settings['organization_social_facebook'])) {
3139 + $social_urls[] = $schema_settings['organization_social_facebook'];
3140 + }
3141 + if (!empty($schema_settings['organization_social_twitter'])) {
3142 + $twitter_url = $schema_settings['organization_social_twitter'];
3143 + // Ensure it's a full URL
3144 + if (strpos($twitter_url, 'http') !== 0) {
3145 + $twitter_url = 'https://twitter.com/' . ltrim($twitter_url, '@');
3146 + }
3147 + $social_urls[] = $twitter_url;
3148 + }
3149 + if (!empty($schema_settings['organization_social_linkedin'])) {
3150 + $social_urls[] = $schema_settings['organization_social_linkedin'];
3151 + }
3152 + if (!empty($schema_settings['organization_social_instagram'])) {
3153 + $social_urls[] = $schema_settings['organization_social_instagram'];
3154 + }
3155 + if (!empty($schema_settings['organization_social_youtube'])) {
3156 + $social_urls[] = $schema_settings['organization_social_youtube'];
3157 + }
3158 + if (!empty($schema_settings['organization_social_pinterest'])) {
3159 + $social_urls[] = $schema_settings['organization_social_pinterest'];
3160 + }
3161 + if (!empty($schema_settings['organization_social_whatsapp'])) {
3162 + $social_urls[] = $schema_settings['organization_social_whatsapp'];
3163 + }
3164 + if (!empty($schema_settings['organization_social_telegram'])) {
3165 + $social_urls[] = $schema_settings['organization_social_telegram'];
3166 + }
3167 +
3168 + // Fallback to Site Identity social profiles if no Schema Manager profiles
3169 + if (empty($social_urls) && !empty($this->site_identity_data['social'])) {
1259 3170 $social_data = $this->site_identity_data['social'];
1260 3171
1261 3172 if (!empty($social_data['facebook_url'])) {
1262 3173 $social_urls[] = $social_data['facebook_url'];
@@ -1280,9 +3191,30 @@
1280 3191 $schema['sameAs'] = $social_urls;
1281 3192 }
1282 3193
1283 3194 // Add contact information if available
1284 - if (!empty($settings['contact_email'])) {
3195 + // Priority: Schema Manager contact info > Site Identity contact info
3196 + if (!empty($schema_settings['organization_contact_phone']) || !empty($schema_settings['organization_contact_email'])) {
3197 + $contact_point = [
3198 + '@type' => 'ContactPoint',
3199 + 'contactType' => $schema_settings['organization_contact_type'] ?? 'customer service'
3200 + ];
3201 +
3202 + if (!empty($schema_settings['organization_contact_phone'])) {
3203 + $contact_point['telephone'] = $schema_settings['organization_contact_phone'];
3204 + }
3205 +
3206 + if (!empty($schema_settings['organization_contact_email'])) {
3207 + $contact_point['email'] = $schema_settings['organization_contact_email'];
3208 + }
3209 +
3210 + if (!empty($schema_settings['organization_contact_hours'])) {
3211 + $contact_point['hoursAvailable'] = $schema_settings['organization_contact_hours'];
3212 + }
3213 +
3214 + $schema['contactPoint'] = $contact_point;
3215 + } elseif (!empty($settings['contact_email'])) {
3216 + // Fallback to Site Identity contact email
1285 3217 $schema['email'] = $settings['contact_email'];
1286 3218 }
1287 3219
1288 3220 return $schema;
@@ -1288,8 +3220,29 @@
1288 3220 return $schema;
1289 3221 }
1290 3222
1291 3223 /**
3224 + * Return the first value that is a non-empty (after trim) string.
3225 + *
3226 + * Settings keys such as organization_url are always present and default to
3227 + * an empty string, so the null-coalescing operator (??) cannot be used to
3228 + * build a fallback chain: '' is not null and would short-circuit the chain.
3229 + * This helper skips empty strings and returns the first real value, falling
3230 + * back to '' when none qualify.
3231 + *
3232 + * @param string|null ...$values Candidate values in priority order.
3233 + * @return string First non-empty value, or '' if none.
3234 + */
3235 + private function first_non_empty(...$values): string {
3236 + foreach ($values as $value) {
3237 + if (is_string($value) && trim($value) !== '') {
3238 + return $value;
3239 + }
3240 + }
3241 + return '';
3242 + }
3243 +
3244 + /**
1292 3245 * Output breadcrumb schema markup
1293 3246 *
1294 3247 * @return void
1295 3248 */
@@ -1297,8 +3250,15 @@
1297 3250 if (!$this->site_identity_data || !$this->site_identity_data['enabled']) {
1298 3251 return;
1299 3252 }
1300 3253
3254 + // A breadcrumb trail for a URL that does not exist, or for a search
3255 + // results page, describes nothing — and the plugin already emits no
3256 + // canonical on either (#471).
3257 + if (is_404() || is_search()) {
3258 + return;
3259 + }
3260 +
1301 3261 $settings = $this->site_identity_manager->get_settings('site');
1302 3262
1303 3263 // Only output if breadcrumbs are enabled
1304 3264 if (empty($settings['breadcrumbs_enabled'])) {
@@ -1304,42 +3264,74 @@
1304 3264 if (empty($settings['breadcrumbs_enabled'])) {
1305 3265 return;
1306 3266 }
1307 3267
3268 + // Schema Manager's own breadcrumb switch. Only Site Identity's
3269 + // breadcrumbs_enabled was consulted here, so enable_breadcrumbs_schema
3270 + // = 0 removed a deployed BreadcrumbList row and left this live one
3271 + // emitting the node anyway (#688). Absent means not configured, which
3272 + // stays enabled.
3273 + if ($this->schema_manager) {
3274 + $schema_settings = $this->schema_manager->get_settings('site', null);
3275 +
3276 + if (array_key_exists('enable_breadcrumbs_schema', $schema_settings)
3277 + && empty($schema_settings['enable_breadcrumbs_schema'])) {
3278 + return;
3279 + }
3280 + }
3281 +
1308 3282 $breadcrumbs = $this->generate_breadcrumbs($settings);
1309 3283
1310 3284 if (!empty($breadcrumbs['schema'])) {
1311 - echo "<!-- ThinkRank SEO Breadcrumb Schema Markup -->\n";
1312 - echo '<script type="application/ld+json">' . "\n";
1313 - echo wp_json_encode($breadcrumbs['schema'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n";
1314 - echo '</script>' . "\n";
1315 - echo "<!-- /ThinkRank SEO Breadcrumb Schema Markup -->\n";
3285 + Schema_Graph::instance()->add_supporting($breadcrumbs['schema'], 'BreadcrumbList');
1316 3286 }
1317 3287 }
1318 3288
1319 3289 /**
3290 + * Emit everything ThinkRank collected for this request as one linked @graph.
3291 + *
3292 + * Runs after every producer has registered (site schema 7, breadcrumbs 8,
3293 + * Global SEO 15), so the graph can arbitrate between them.
3294 + *
3295 + * @since 1.32.0
3296 + * @return void
3297 + */
3298 + public function output_schema_graph(): void {
3299 + Schema_Graph::instance()->render();
3300 + }
3301 +
3302 + /**
1320 3303 * Output closing comment for ThinkRank SEO
1321 3304 *
1322 3305 * @return void
1323 3306 */
1324 3307 public function output_closing_comment(): void {
1325 - // Only output if we've output any SEO content
1326 - static $header_output = false;
1327 - if ($header_output || $this->has_seo_output()) {
3308 + // Close only what was actually opened. has_seo_output() is true on
3309 + // nearly every page, so testing it here printed a closing comment with
3310 + // no matching opener whenever the meta description was empty (search
3311 + // results, author archives without a description).
3312 + if (self::$opening_comment_output) {
1328 3313 echo "<!-- /ThinkRank SEO -->\n";
1329 3314 }
1330 3315 }
1331 3316
1332 3317 /**
1333 - * Check if any SEO content has been output
3318 + * Print the opening ThinkRank comment, once per request.
1334 3319 *
1335 - * @return bool True if SEO content was output
3320 + * Public and static so Author_Archives_Manager — which prints its own meta
3321 + * description on wp_head at priority 5 — opens the block through the same
3322 + * flag the closing comment reads.
3323 + *
3324 + * @since 2.0.1
3325 + * @return void
1336 3326 */
1337 - private function has_seo_output(): bool {
1338 - // Check if we have meta description or any other SEO data
1339 - return !empty($this->get_meta_description()) ||
1340 - $this->has_thinkrank_metadata() ||
1341 - ($this->site_identity_data && $this->site_identity_data['enabled']);
3327 + public static function note_opening_comment(): void {
3328 + if (self::$opening_comment_output) {
3329 + return;
3330 + }
3331 +
3332 + echo "<!-- Search Engine Optimization by ThinkRank - https://thinkrank.ai/ -->\n";
3333 + self::$opening_comment_output = true;
1342 3334 }
1343 3335
1344 3336 /**
1345 3337 * Display breadcrumbs HTML
@@ -1366,8 +3358,144 @@
1366 3358 }
1367 3359 }
1368 3360
1369 3361 /**
3362 + * Render breadcrumbs for the [thinkrank_breadcrumbs] shortcode
3363 + *
3364 + * Respects the same site-identity / breadcrumbs_enabled gates as
3365 + * display_breadcrumbs().
3366 + *
3367 + * @return string Breadcrumb HTML (empty string when disabled)
3368 + */
3369 + public function breadcrumbs_shortcode(): string {
3370 + ob_start();
3371 + $this->display_breadcrumbs();
3372 + return (string) ob_get_clean();
3373 + }
3374 +
3375 + /**
3376 + * Display the hero section for the `thinkrank_hero` action hook /
3377 + * `thinkrank_hero()` template tag.
3378 + *
3379 + * Gated on the Site Identity master toggle. Emits nothing when no hero
3380 + * content (title/subtitle/CTA) is configured, so an empty hero never
3381 + * appears on the front end.
3382 + *
3383 + * @return void
3384 + */
3385 + public function display_hero(): void {
3386 + if (!$this->site_identity_data || !$this->site_identity_data['enabled']) {
3387 + return;
3388 + }
3389 +
3390 + $settings = $this->site_identity_manager->get_settings('site');
3391 + $html = $this->generate_hero_html($settings);
3392 +
3393 + if ($html !== '') {
3394 + // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML is escaped field-by-field in generate_hero_html().
3395 + echo $html;
3396 + }
3397 + }
3398 +
3399 + /**
3400 + * Render the hero section for the [thinkrank_hero] shortcode.
3401 + *
3402 + * Respects the same gates as display_hero().
3403 + *
3404 + * @return string Hero HTML (empty string when disabled or unconfigured)
3405 + */
3406 + public function hero_shortcode(): string {
3407 + ob_start();
3408 + $this->display_hero();
3409 + return (string) ob_get_clean();
3410 + }
3411 +
3412 + /**
3413 + * Get the current hero section data without displaying it.
3414 + *
3415 + * @return array|null Hero data (title, subtitle, cta_text, cta_url,
3416 + * background_image, html) or null when unavailable.
3417 + */
3418 + public function get_current_hero(): ?array {
3419 + if (!$this->site_identity_data || !$this->site_identity_data['enabled']) {
3420 + return null;
3421 + }
3422 +
3423 + $settings = $this->site_identity_manager->get_settings('site');
3424 +
3425 + $hero = [
3426 + 'title' => (string) ($settings['hero_title'] ?? ''),
3427 + 'subtitle' => (string) ($settings['hero_subtitle'] ?? ''),
3428 + 'cta_text' => (string) ($settings['hero_cta_text'] ?? ''),
3429 + 'cta_url' => (string) ($settings['hero_cta_url'] ?? ''),
3430 + 'background_image' => (string) ($settings['hero_background_image'] ?? ''),
3431 + ];
3432 +
3433 + // generate_hero_html() is the single source of truth for the
3434 + // "is anything renderable?" gate (title, subtitle, or a complete CTA),
3435 + // so defer to it rather than duplicate the check — and never expose an
3436 + // empty hero.
3437 + $hero['html'] = $this->generate_hero_html($settings);
3438 + if ($hero['html'] === '') {
3439 + return null;
3440 + }
3441 +
3442 + return $hero;
3443 + }
3444 +
3445 + /**
3446 + * Build the hero section HTML from Site Identity settings.
3447 + *
3448 + * Every dynamic value is escaped at the point of output. Returns an empty
3449 + * string when there is no title, subtitle, or complete CTA (text + URL).
3450 + *
3451 + * @param array $settings Site Identity settings
3452 + * @return string Hero HTML, or '' when there is nothing to render
3453 + */
3454 + private function generate_hero_html(array $settings): string {
3455 + $title = trim((string) ($settings['hero_title'] ?? ''));
3456 + $subtitle = trim((string) ($settings['hero_subtitle'] ?? ''));
3457 + $cta_text = trim((string) ($settings['hero_cta_text'] ?? ''));
3458 + $cta_url = trim((string) ($settings['hero_cta_url'] ?? ''));
3459 + $bg_image = trim((string) ($settings['hero_background_image'] ?? ''));
3460 +
3461 + // A CTA is only meaningful with both a label and a destination.
3462 + $has_cta = ($cta_text !== '' && $cta_url !== '');
3463 +
3464 + // Don't emit an empty hero when nothing renderable is configured. A
3465 + // background image alone — or CTA text without a URL — is not enough.
3466 + if ($title === '' && $subtitle === '' && !$has_cta) {
3467 + return '';
3468 + }
3469 +
3470 + $classes = ['thinkrank-hero'];
3471 + $style = '';
3472 + if ($bg_image !== '') {
3473 + $classes[] = 'thinkrank-hero--has-image';
3474 + $style = ' style="background-image:url(' . esc_url($bg_image) . ');"';
3475 + }
3476 +
3477 + $html = '<section class="' . esc_attr(implode(' ', $classes)) . '"' . $style . '>';
3478 + $html .= '<div class="thinkrank-hero__inner">';
3479 +
3480 + if ($title !== '') {
3481 + $html .= '<h2 class="thinkrank-hero__title">' . esc_html($title) . '</h2>';
3482 + }
3483 +
3484 + if ($subtitle !== '') {
3485 + $html .= '<p class="thinkrank-hero__subtitle">' . esc_html($subtitle) . '</p>';
3486 + }
3487 +
3488 + if ($has_cta) {
3489 + $html .= '<a class="thinkrank-hero__cta" href="' . esc_url($cta_url) . '">' . esc_html($cta_text) . '</a>';
3490 + }
3491 +
3492 + $html .= '</div></section>';
3493 +
3494 + return $html;
3495 + }
3496 +
3497 + /**
1370 3498 * Generate breadcrumbs data
1371 3499 *
1372 3500 * @param array $settings Breadcrumb settings
1373 3501 * @return array Breadcrumb data with HTML and schema
@@ -1397,15 +3525,158 @@
1397 3525 return $breadcrumbs;
1398 3526 }
1399 3527
1400 3528 /**
3529 + * Serve /llms.txt through PHP so the response declares UTF-8.
3530 + *
3531 + * Cheap guard first: every other front-end request leaves without loading
3532 + * the manager.
3533 + *
3534 + * @since 1.32.0
3535 + *
3536 + * @return void
3537 + */
3538 + /**
3539 + * Serve a ThinkRank sitemap document for this request, when it is one.
3540 + *
3541 + * Only acts in dynamic delivery mode. In static mode a real file exists and
3542 + * the web server returns it without WordPress ever loading, so answering
3543 + * here as well would mean two sources for the same bytes.
3544 + *
3545 + * @since 2.9.0
3546 + *
3547 + * @return void
3548 + */
3549 + public function maybe_serve_sitemap(): void {
3550 + $filename = $this->requested_sitemap_filename();
3551 + if ('' === $filename) {
3552 + return;
3553 + }
3554 +
3555 + try {
3556 + // Read-only instance: passing false keeps it from registering a
3557 + // second copy of the auto-generation hooks.
3558 + $generator = new \ThinkRank\SEO\Sitemap_Generator(false);
3559 + $settings = $generator->get_settings('site');
3560 +
3561 + if (empty($settings['enabled'])) {
3562 + return;
3563 + }
3564 +
3565 + if ('dynamic' !== $generator->resolve_delivery_mode($settings)) {
3566 + return;
3567 + }
3568 +
3569 + if (!$generator->publishes_document_name($filename, $settings)) {
3570 + return;
3571 + }
3572 +
3573 + $xml = $generator->render_document($filename, $settings);
3574 + } catch (\Throwable $e) {
3575 + // A failed render must not replace the sitemap with a fatal. Leave
3576 + // the request alone so WordPress answers as it otherwise would.
3577 + return;
3578 + }
3579 +
3580 + if (!is_string($xml) || '' === trim($xml)) {
3581 + return;
3582 + }
3583 +
3584 + status_header(200);
3585 + header('Content-Type: application/xml; charset=UTF-8');
3586 + header('X-Robots-Tag: noindex, follow', true);
3587 +
3588 + // Built XML, escaped by the builders as they assemble it; escaping the
3589 + // document here would corrupt it.
3590 + echo $xml; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
3591 + exit;
3592 + }
3593 +
3594 + /**
3595 + * The sitemap file name this request is asking for, if it looks like one.
3596 + *
3597 + * Deliberately a cheap shape test. Whether the site actually publishes the
3598 + * name is settled by the caller against the generator, so that a request
3599 + * for someone else's sitemap is never answered here.
3600 + *
3601 + * @since 2.9.0
3602 + *
3603 + * @return string File name, or '' when this is not a sitemap request.
3604 + */
3605 + private function requested_sitemap_filename(): string {
3606 + if (empty($_SERVER['REQUEST_URI'])) {
3607 + return '';
3608 + }
3609 +
3610 + $path = wp_parse_url(sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])), PHP_URL_PATH);
3611 + if (!is_string($path) || '' === $path) {
3612 + return '';
3613 + }
3614 +
3615 + // Strip the install's home path so subdirectory installs match too.
3616 + $home_path = (string) wp_parse_url(home_url('/'), PHP_URL_PATH);
3617 + if ('' !== $home_path && '/' !== $home_path && 0 === strpos($path, $home_path)) {
3618 + $path = substr($path, strlen($home_path));
3619 + }
3620 +
3621 + $candidate = strtolower(trim($path, '/'));
3622 +
3623 + // One path segment ending in .xml. Anything nested is not a file we
3624 + // publish to the web root.
3625 + if ('' === $candidate || strpos($candidate, '/') !== false) {
3626 + return '';
3627 + }
3628 +
3629 + return substr($candidate, -4) === '.xml' ? $candidate : '';
3630 + }
3631 +
3632 + public function maybe_serve_llms_txt(): void {
3633 + if (!$this->is_llms_txt_request()) {
3634 + return;
3635 + }
3636 +
3637 + if (!class_exists('ThinkRank\\SEO\\LLMs_Txt_Manager')) {
3638 + require_once THINKRANK_PLUGIN_DIR . 'includes/seo/class-llms-txt-manager.php';
3639 + }
3640 +
3641 + $manager = new \ThinkRank\SEO\LLMs_Txt_Manager();
3642 + $manager->serve_llms_txt();
3643 + }
3644 +
3645 + /**
3646 + * Whether the current request is for /llms.txt.
3647 + *
3648 + * @since 1.32.0
3649 + *
3650 + * @return bool
3651 + */
3652 + private function is_llms_txt_request(): bool {
3653 + if (empty($_SERVER['REQUEST_URI'])) {
3654 + return false;
3655 + }
3656 +
3657 + $path = wp_parse_url(sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI'])), PHP_URL_PATH);
3658 + if (!is_string($path) || '' === $path) {
3659 + return false;
3660 + }
3661 +
3662 + // Strip the install's home path so subdirectory installs match too.
3663 + $home_path = (string) wp_parse_url(home_url('/'), PHP_URL_PATH);
3664 + if ('' !== $home_path && '/' !== $home_path && 0 === strpos($path, $home_path)) {
3665 + $path = substr($path, strlen($home_path));
3666 + }
3667 +
3668 + return 'llms.txt' === strtolower(trim($path, '/'));
3669 + }
3670 +
3671 + /**
1401 3672 * Filter WordPress robots.txt output
1402 3673 *
1403 3674 * @param string $output The default robots.txt output
1404 - * @param string $public Whether the site is public
3675 + * @param string $is_public Whether the site is public
1405 3676 * @return string Modified robots.txt content
1406 3677 */
1407 - public function filter_robots_txt(string $output, string $public): string {
3678 + public function filter_robots_txt(string $output, string $is_public): string {
1408 3679 // Only override if Site Identity is enabled and robots.txt management is enabled
1409 3680 if (!$this->site_identity_data || !$this->site_identity_data['enabled']) {
1410 3681 return $output;
1411 3682 }
@@ -1414,24 +3685,443 @@
1414 3685 if (empty($settings['robots_txt_enabled'])) {
1415 3686 return $output;
1416 3687 }
1417 3688
1418 - // Generate ThinkRank robots.txt content
3689 + // Serve the effective content (manual textarea edit if present, else
3690 + // auto-generated) so the live /robots.txt matches what the admin sees.
1419 3691 try {
1420 - $robots_data = $this->site_identity_manager->generate_robots_txt();
3692 + $content = $this->site_identity_manager->render_robots_txt();
1421 3693
1422 - if (!empty($robots_data['content'])) {
1423 - return $robots_data['content'];
3694 + if (!empty($content)) {
3695 + return $content;
1424 3696 }
1425 3697 } catch (\Exception $e) {
1426 - // Robots.txt generation failed - fallback to default output
3698 + // Rendering failed - fall back to default output
1427 3699 }
1428 3700
1429 - // Fallback to default output if generation fails
3701 + // Fallback to default output if rendering fails
1430 3702 return $output;
1431 3703 }
1432 3704
1433 3705 /**
3706 + * Disable WordPress core's sitemap while ThinkRank's sitemap is enabled.
3707 + *
3708 + * Prevents the site from publishing two competing sitemap indexes. Core's
3709 + * /wp-sitemap.xml is taken offline (it 404s) and, as a consequence, core
3710 + * stops adding its own "Sitemap:" directive to robots.txt — including on the
3711 + * paths where ThinkRank does not own the robots.txt output.
3712 + *
3713 + * Only ever turns core's sitemap *off*: when ThinkRank's sitemap is disabled
3714 + * the incoming value is returned untouched, so core (or another plugin
3715 + * filtering this) keeps whatever behaviour it already had.
3716 + *
3717 + * @since 1.31.0
3718 + *
3719 + * @param bool $enabled Whether core's sitemap functionality is enabled.
3720 + * @return bool Filtered value.
3721 + */
3722 + public function filter_wp_sitemaps_enabled($enabled): bool {
3723 + return $this->should_disable_core_sitemap() ? false : (bool) $enabled;
3724 + }
3725 +
3726 + /**
3727 + * Redirect the sitemap URLs core owns to the sitemap ThinkRank publishes.
3728 + *
3729 + * Only the *index* route is redirected. Core's per-type children
3730 + * (/wp-sitemap-posts-post-1.xml and friends) are genuinely gone once core is
3731 + * switched off, and a 404 is the honest answer for those; the index is the
3732 + * one URL crawlers and humans actually guess, and the one core's own
3733 + * /sitemap.xml rule funnels into.
3734 + *
3735 + * @since 1.31.0
3736 + *
3737 + * @return void
3738 + */
3739 + public function redirect_core_sitemap_requests(): void {
3740 + if ('index' !== get_query_var('sitemap')) {
3741 + return;
3742 + }
3743 +
3744 + $request_uri = isset($_SERVER['REQUEST_URI'])
3745 + ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_URI']))
3746 + : '';
3747 +
3748 + $target = $this->resolve_core_sitemap_redirect(
3749 + (string) wp_parse_url($request_uri, PHP_URL_PATH)
3750 + );
3751 +
3752 + if ('' === $target) {
3753 + return;
3754 + }
3755 +
3756 + wp_safe_redirect($target, 301, 'ThinkRank');
3757 + exit;
3758 + }
3759 +
3760 + /**
3761 + * Where a request for one of core's sitemap URLs should be sent, if anywhere.
3762 + *
3763 + * Split out from the hook so the rules are testable without dispatching a
3764 + * request — the caller above is the only part that cannot be (it exits).
3765 + *
3766 + * @since 1.31.0
3767 + *
3768 + * @param string $requested_path Path of the incoming request.
3769 + * @return string Absolute URL to redirect to, or '' to leave the request alone.
3770 + */
3771 + private function resolve_core_sitemap_redirect(string $requested_path): string {
3772 + // Nothing to redirect to unless we have actually taken core offline,
3773 + // which already implies our own sitemap file is on disk.
3774 + if (!$this->should_disable_core_sitemap()) {
3775 + return '';
3776 + }
3777 +
3778 + $target = $this->thinkrank_sitemap_url;
3779 + if ('' === $target) {
3780 + return '';
3781 + }
3782 +
3783 + // Never redirect a URL to itself. A site publishing at /sitemap.xml
3784 + // normally has the web server serve that file before WordPress sees the
3785 + // request, but on a setup where the request does reach PHP this is the
3786 + // difference between a redirect and a loop.
3787 + $destination = (string) wp_parse_url($target, PHP_URL_PATH);
3788 +
3789 + if ('' !== $requested_path && untrailingslashit($requested_path) === untrailingslashit($destination)) {
3790 + return '';
3791 + }
3792 +
3793 + return $target;
3794 + }
3795 +
3796 + /**
3797 + * Whether core's sitemap should be switched off for this site.
3798 + *
3799 + * True when ThinkRank publishes its own sitemap — except in two cases where
3800 + * taking core offline would leave a URL answering nothing:
3801 + *
3802 + * 1. The site is configured to publish *at core's own URL* (the "WordPress
3803 + * Core" preset). Once the static file exists the web server serves it
3804 + * ahead of WordPress anyway, so core can be left alone.
3805 + * 2. ThinkRank's own sitemap file is not on disk yet. Sitemaps here are
3806 + * static files with no dynamic route (see save_sitemap_to_file()), so
3807 + * while the file is missing core's /sitemap.xml -> /wp-sitemap.xml
3808 + * redirect is the only thing answering that URL; suppressing core would
3809 + * turn a recoverable "enabled but not generated" state into a hard 404
3810 + * for crawlers. Core is taken offline as soon as our file appears, so the
3811 + * duplicate-index conflict this filter exists to prevent cannot occur —
3812 + * two indexes are only ever reachable if both are actually published.
3813 + *
3814 + * Once our file does exist, the URLs core stops answering are handed to
3815 + * redirect_core_sitemap_requests() rather than left to 404 — which is why
3816 + * this also resolves the destination.
3817 + *
3818 + * Resolved lazily and memoised: this is consulted from an `init`-time filter
3819 + * on every request, and the underlying settings read is object-cached. The
3820 + * memoisation also keeps the file_exists() call to one per request.
3821 + *
3822 + * @since 1.31.0
3823 + *
3824 + * @return bool True when WordPress core's sitemap should be disabled.
3825 + */
3826 + private function should_disable_core_sitemap(): bool {
3827 + if ($this->thinkrank_sitemap_enabled === null) {
3828 + try {
3829 + // Read-only instance — passing false keeps it from registering a
3830 + // second copy of the save_post/term auto-generation hooks.
3831 + $generator = new \ThinkRank\SEO\Sitemap_Generator(false);
3832 + $settings = $generator->get_settings('site');
3833 +
3834 + // "Can ThinkRank actually answer its sitemap URL right now?" In
3835 + // static mode that means the file is on disk; in dynamic mode
3836 + // maybe_serve_sitemap() answers it, so there is nothing to look
3837 + // for. Keeping the file test as the only answer would have left
3838 + // core's sitemap in place on every dynamic site, which is the
3839 + // crawl conflict this suppression exists to prevent (#752).
3840 + // The #346 behaviour is unchanged: a static site with nothing
3841 + // published still falls through to core rather than 404ing.
3842 + $can_serve = 'dynamic' === $generator->resolve_delivery_mode($settings)
3843 + || $generator->primary_sitemap_file_exists($settings);
3844 +
3845 + $this->thinkrank_sitemap_enabled = !empty($settings['enabled'])
3846 + && !$this->publishes_at_core_sitemap_url($settings)
3847 + && $can_serve;
3848 +
3849 + if ($this->thinkrank_sitemap_enabled) {
3850 + $this->thinkrank_sitemap_url = $generator->get_primary_sitemap_url($settings);
3851 + }
3852 + } catch (\Exception $e) {
3853 + // Settings unreadable — leave core's sitemap alone rather than
3854 + // removing a working sitemap on the strength of a failed read.
3855 + $this->thinkrank_sitemap_enabled = false;
3856 + $this->thinkrank_sitemap_url = '';
3857 + }
3858 + }
3859 +
3860 + return $this->thinkrank_sitemap_enabled;
3861 + }
3862 +
3863 + /**
3864 + * Whether any configured sitemap URL is WordPress core's own wp-sitemap.xml.
3865 + *
3866 + * @since 1.31.0
3867 + *
3868 + * @param array $settings Sitemap settings.
3869 + * @return bool True when the site publishes at core's sitemap URL.
3870 + */
3871 + private function publishes_at_core_sitemap_url(array $settings): bool {
3872 + foreach ((array) ($settings['sitemap_urls'] ?? []) as $sitemap) {
3873 + if (!is_array($sitemap)) {
3874 + continue;
3875 + }
3876 +
3877 + $path = (string) wp_parse_url((string) ($sitemap['url'] ?? ''), PHP_URL_PATH);
3878 +
3879 + if (ltrim($path, '/') === 'wp-sitemap.xml') {
3880 + return true;
3881 + }
3882 + }
3883 +
3884 + return false;
3885 + }
3886 +
3887 + /**
3888 + * Re-sync the physical robots.txt when WordPress's "Discourage search
3889 + * engines" setting (blog_public) changes.
3890 + *
3891 + * Only acts when ThinkRank robots management is enabled AND a physical
3892 + * robots.txt already exists — a stale physical file is the failure being
3893 + * fixed. When no file exists the virtual robots_txt filter already reflects
3894 + * blog_public live (render_robots_txt() enforces the full block), so there is
3895 + * nothing to re-sync and no reason to create a file the user never generated.
3896 + *
3897 + * @return void
3898 + */
3899 + public function on_blog_public_changed(): void {
3900 + if (!$this->site_identity_manager) {
3901 + return;
3902 + }
3903 +
3904 + // Gate on robots management (robots_txt_enabled), not the Site Identity
3905 + // master toggle: the physical file's lifecycle is governed by that
3906 + // setting alone (same as sync_robots_txt_file() and the save endpoint),
3907 + // and a stale physical file is served by the web server regardless of the
3908 + // master toggle.
3909 + $settings = $this->site_identity_manager->get_settings('site');
3910 + if (empty($settings['robots_txt_enabled'])) {
3911 + return;
3912 + }
3913 +
3914 + if (file_exists(ABSPATH . 'robots.txt')) {
3915 + $this->site_identity_manager->sync_robots_txt_file();
3916 + }
3917 + }
3918 +
3919 + /**
3920 + * Use the Site Identity favicon as the site icon URL
3921 + *
3922 + * When a favicon is uploaded in ThinkRank Site Identity it takes
3923 + * precedence over the core site icon; with no core icon set this also
3924 + * makes has_site_icon() truthy so wp_site_icon() prints the icon tags.
3925 + * Reads settings directly (not site_identity_data) because this filter
3926 + * also runs in admin, before initialize_current_context().
3927 + *
3928 + * @param string $url Site icon URL from core
3929 + * @param int $size Requested icon size
3930 + * @return string Icon URL
3931 + */
3932 + public function filter_site_icon_url($url, $size = 512): string {
3933 + $settings = $this->site_identity_manager->get_settings('site');
3934 +
3935 + if (empty($settings['enabled'])) {
3936 + return (string) $url;
3937 + }
3938 +
3939 + $size = (int) $size;
3940 +
3941 + // Apple touch icon has its own dedicated setting
3942 + if ($size === 180 && !empty($settings['apple_touch_icon_url'])) {
3943 + return $this->resolve_icon_url((string) $settings['apple_touch_icon_url'], $size);
3944 + }
3945 +
3946 + if (!empty($settings['favicon_url'])) {
3947 + return $this->resolve_icon_url((string) $settings['favicon_url'], $size);
3948 + }
3949 +
3950 + return (string) $url;
3951 + }
3952 +
3953 + /**
3954 + * Whether breadcrumb labels should prefer the SEO title.
3955 + *
3956 + * Off unless the site turns it on, so updating the plugin never rewrites an
3957 + * existing trail.
3958 + *
3959 + * @since 2.3.1
3960 + *
3961 + * @param array $settings Breadcrumb settings.
3962 + * @return bool
3963 + */
3964 + private function breadcrumbs_use_seo_title(array $settings): bool {
3965 + return !empty($settings['breadcrumb_use_seo_title']);
3966 + }
3967 +
3968 + /**
3969 + * Label for a post in the breadcrumb trail.
3970 + *
3971 + * With the toggle on, the post's own SEO title wins — the same
3972 + * `_thinkrank_seo_title` value (variable tags resolved) the document title
3973 + * uses — so the trail under a search snippet reads the same as the snippet
3974 + * itself. Anything empty falls back to the raw post title; the global title
3975 + * pattern is deliberately NOT part of the chain, since resolving it would
3976 + * append the site name to every crumb.
3977 + *
3978 + * @since 2.3.1
3979 + *
3980 + * @param int $post_id Post ID.
3981 + * @param array $settings Breadcrumb settings.
3982 + * @return string Breadcrumb label.
3983 + */
3984 + private function get_breadcrumb_post_title(int $post_id, array $settings): string {
3985 + $title = (string) get_the_title($post_id);
3986 +
3987 + if (!$this->breadcrumbs_use_seo_title($settings)) {
3988 + return $title;
3989 + }
3990 +
3991 + $seo_title = trim((string) get_post_meta($post_id, '_thinkrank_seo_title', true));
3992 +
3993 + if ('' === $seo_title) {
3994 + return $title;
3995 + }
3996 +
3997 + $resolved = trim(\ThinkRank\SEO\Pattern_Resolver::resolve_value($seo_title, $post_id));
3998 +
3999 + return '' !== $resolved ? $resolved : $title;
4000 + }
4001 +
4002 + /**
4003 + * Label for a term in the breadcrumb trail.
4004 + *
4005 + * Term counterpart to {@see self::get_breadcrumb_post_title()}, resolving
4006 + * the term's `_thinkrank_seo_title` against its own values.
4007 + *
4008 + * @since 2.3.1
4009 + *
4010 + * @param object $term Term object.
4011 + * @param array $settings Breadcrumb settings.
4012 + * @return string Breadcrumb label.
4013 + */
4014 + private function get_breadcrumb_term_title($term, array $settings): string {
4015 + $name = (string) ($term->name ?? '');
4016 +
4017 + if (!$this->breadcrumbs_use_seo_title($settings) || empty($term->term_id)) {
4018 + return $name;
4019 + }
4020 +
4021 + $seo_title = trim((string) get_term_meta((int) $term->term_id, '_thinkrank_seo_title', true));
4022 +
4023 + if ('' === $seo_title) {
4024 + return $name;
4025 + }
4026 +
4027 + $resolved = trim(\ThinkRank\SEO\Pattern_Resolver::resolve_term_value($seo_title, (int) $term->term_id));
4028 +
4029 + return '' !== $resolved ? $resolved : $name;
4030 + }
4031 +
4032 + /**
4033 + * Resolve a configured icon URL to the derivative that fits $size.
4034 + *
4035 + * wp_site_icon() calls get_site_icon_url() four times — 32, 192, 180 and
4036 + * 270 — and pairs the first two with a hardcoded sizes="" attribute. This
4037 + * filter used to answer all four with the same configured URL, so one
4038 + * upload was declared as every size at once: a 1536x1536 original served
4039 + * to paint a 32px tab icon, under a sizes="32x32" label that was simply
4040 + * untrue (#571).
4041 + *
4042 + * Resolution mirrors core's own get_site_icon_url(), including the
4043 + * >= 512 -> 'full' branch, so ThinkRank's override and the core pipeline
4044 + * pick the same file for the same request.
4045 + *
4046 + * An unresolvable URL (one hosted off-site) is returned unchanged. Nothing
4047 + * is knowable about its dimensions, and suppressing it instead would leave
4048 + * the page with no rel="icon" at all — a worse outcome than an approximate
4049 + * size hint.
4050 + *
4051 + * @param string $configured Configured icon URL.
4052 + * @param int $size Icon size core is asking for.
4053 + * @return string Icon URL for that size.
4054 + */
4055 + private function resolve_icon_url(string $configured, int $size): string {
4056 + $cache_key = md5($configured) . ':' . $size;
4057 + $cached = $this->icon_urls();
4058 +
4059 + if (isset($cached[$cache_key])) {
4060 + return $cached[$cache_key];
4061 + }
4062 +
4063 + $attachment_id = \ThinkRank\SEO\Site_Identity_Manager::icon_attachment_id($configured);
4064 +
4065 + if (!$attachment_id) {
4066 + $resolved = esc_url($configured);
4067 + } else {
4068 + // Mirrors core: at 512 and above the original is what is wanted, and
4069 + // asking for an intermediate size that large would only fall back to it.
4070 + $size_data = $size >= 512 ? 'full' : [$size, $size];
4071 + $url = wp_get_attachment_image_url($attachment_id, $size_data);
4072 + $resolved = $url ? esc_url($url) : esc_url($configured);
4073 + }
4074 +
4075 + $this->icon_urls[$cache_key] = $resolved;
4076 +
4077 + if (!$this->icon_urls_dirty) {
4078 + $this->icon_urls_dirty = true;
4079 + // Written once, after the response is assembled, rather than once
4080 + // per size: wp_site_icon() resolves four in a row.
4081 + add_action('shutdown', [$this, 'persist_icon_urls'], 5);
4082 + }
4083 +
4084 + return $resolved;
4085 + }
4086 +
4087 + /**
4088 + * The resolved-icon-URL map, loaded from its transient on first use.
4089 + *
4090 + * @return array<string, string>
4091 + */
4092 + private function icon_urls(): array {
4093 + if ($this->icon_urls === null) {
4094 + $stored = get_transient(\ThinkRank\SEO\Site_Identity_Manager::ICON_URL_TRANSIENT);
4095 + $this->icon_urls = is_array($stored) ? $stored : [];
4096 + }
4097 +
4098 + return $this->icon_urls;
4099 + }
4100 +
4101 + /**
4102 + * Persist newly resolved icon URLs.
4103 + *
4104 + * Public because it runs on `shutdown`. Invalidated wholesale whenever the
4105 + * site identity settings are saved, which is the only moment the icon
4106 + * choice — or the derivatives behind it — can change.
4107 + *
4108 + * @return void
4109 + */
4110 + public function persist_icon_urls(): void {
4111 + if (!$this->icon_urls_dirty || !is_array($this->icon_urls)) {
4112 + return;
4113 + }
4114 +
4115 + $this->icon_urls_dirty = false;
4116 + set_transient(
4117 + \ThinkRank\SEO\Site_Identity_Manager::ICON_URL_TRANSIENT,
4118 + $this->icon_urls,
4119 + DAY_IN_SECONDS
4120 + );
4121 + }
4122 +
4123 + /**
1434 4124 * Get breadcrumb items for current page
1435 4125 *
1436 4126 * @param array $settings Breadcrumb settings
1437 4127 * @return array Breadcrumb items
@@ -1459,9 +4149,9 @@
1459 4149 $categories = get_the_category($current_post_id);
1460 4150 if (!empty($categories)) {
1461 4151 $category = $categories[0];
1462 4152 $items[] = [
1463 - 'title' => $category->name,
4153 + 'title' => $this->get_breadcrumb_term_title($category, $settings),
1464 4154 'url' => get_category_link($category->term_id),
1465 4155 'position' => $position++
1466 4156 ];
1467 4157 }
@@ -1466,12 +4156,18 @@
1466 4156 ];
1467 4157 }
1468 4158 }
1469 4159
1470 - // Add current post
1471 - if (empty($settings['show_current_page']) || $settings['show_current_page']) {
4160 + // Add current post. `empty($x) || $x` is true for every possible
4161 + // value — an unset key, false, 0, '' and any truthy value alike —
4162 + // so the setting had no effect on the rendered breadcrumb or on
4163 + // the BreadcrumbList JSON-LD, while the admin preview honoured it
4164 + // and disagreed with live output (#398). Site_Identity_Manager
4165 + // already had the correct form: default to on, respect an
4166 + // explicit off.
4167 + if ($settings['show_current_page'] ?? true) {
1472 4168 $items[] = [
1473 - 'title' => get_the_title($current_post_id),
4169 + 'title' => $this->get_breadcrumb_post_title($current_post_id, $settings),
1474 4170 'url' => get_permalink($current_post_id),
1475 4171 'position' => $position,
1476 4172 'current' => true
1477 4173 ];
@@ -1476,9 +4172,8 @@
1476 4172 'current' => true
1477 4173 ];
1478 4174 }
1479 4175 }
1480 -
1481 4176 } elseif (is_page()) {
1482 4177 $current_post_id = get_the_ID();
1483 4178
1484 4179 if ($current_post_id) {
@@ -1489,9 +4184,9 @@
1489 4184 while ($parent_id) {
1490 4185 $parent = get_post($parent_id);
1491 4186 if ($parent) {
1492 4187 $parents[] = [
1493 - 'title' => get_the_title($parent->ID),
4188 + 'title' => $this->get_breadcrumb_post_title($parent->ID, $settings),
1494 4189 'url' => get_permalink($parent->ID),
1495 4190 'position' => 0 // Will be set later
1496 4191 ];
1497 4192 $parent_id = $parent->post_parent;
@@ -1509,11 +4204,11 @@
1509 4204 $items[] = $parent;
1510 4205 }
1511 4206
1512 4207 // Add current page
1513 - if (empty($settings['show_current_page']) || $settings['show_current_page']) {
4208 + if ($settings['show_current_page'] ?? true) {
1514 4209 $items[] = [
1515 - 'title' => get_the_title($current_post_id),
4210 + 'title' => $this->get_breadcrumb_post_title($current_post_id, $settings),
1516 4211 'url' => get_permalink($current_post_id),
1517 4212 'position' => $position,
1518 4213 'current' => true
1519 4214 ];
@@ -1518,9 +4213,8 @@
1518 4213 'current' => true
1519 4214 ];
1520 4215 }
1521 4216 }
1522 -
1523 4217 } elseif (is_category()) {
1524 4218 $category = get_queried_object();
1525 4219
1526 4220 // Add parent categories
@@ -1530,9 +4224,9 @@
1530 4224 while ($parent_id) {
1531 4225 $parent = get_category($parent_id);
1532 4226 if ($parent && !is_wp_error($parent)) {
1533 4227 $parents[] = [
1534 - 'title' => $parent->name,
4228 + 'title' => $this->get_breadcrumb_term_title($parent, $settings),
1535 4229 'url' => get_category_link($parent->term_id),
1536 4230 'position' => 0 // Will be set later
1537 4231 ];
1538 4232 $parent_id = $parent->parent;
@@ -1550,11 +4244,11 @@
1550 4244 $items[] = $parent;
1551 4245 }
1552 4246
1553 4247 // Add current category
1554 - if (empty($settings['show_current_page']) || $settings['show_current_page']) {
4248 + if ($settings['show_current_page'] ?? true) {
1555 4249 $items[] = [
1556 - 'title' => $category->name,
4250 + 'title' => $this->get_breadcrumb_term_title($category, $settings),
1557 4251 'url' => get_category_link($category->term_id),
1558 4252 'position' => $position,
1559 4253 'current' => true
1560 4254 ];
@@ -1643,70 +4337,8 @@
1643 4337 ];
1644 4338 }
1645 4339
1646 4340 /**
1647 - * Debug method to verify priority system (remove in production)
1648 - *
1649 - * @return array Debug information about current page SEO data
1650 - */
1651 - public function debug_seo_priority(): array {
1652 - if (!defined('WP_DEBUG') || !WP_DEBUG) {
1653 - return [];
1654 - }
1655 -
1656 - $debug = [
1657 - 'context' => $this->current_context,
1658 - 'is_singular' => is_singular(),
1659 - 'post_id' => $this->current_post_id,
1660 - 'has_post_metadata' => $this->has_thinkrank_metadata(),
1661 - 'post_metadata' => $this->current_metadata,
1662 - 'site_identity_enabled' => $this->site_identity_data && $this->site_identity_data['enabled'],
1663 - 'final_title' => '',
1664 - 'final_description' => '',
1665 - 'title_source' => '',
1666 - 'description_source' => ''
1667 - ];
1668 -
1669 - // Determine title source
1670 - if ($this->has_thinkrank_metadata() && !empty($this->current_metadata['title'])) {
1671 - $debug['final_title'] = $this->current_metadata['title'];
1672 - $debug['title_source'] = 'post_metadata';
1673 - } else {
1674 - $generated_title = $this->generate_context_title();
1675 - if ($generated_title) {
1676 - $debug['final_title'] = $generated_title;
1677 - $debug['title_source'] = 'site_identity_template';
1678 - } else {
1679 - $debug['final_title'] = is_singular() ? get_the_title() : get_bloginfo('name');
1680 - $debug['title_source'] = 'wordpress_default';
1681 - }
1682 - }
1683 -
1684 - // Determine description source
1685 - $description = $this->get_meta_description();
1686 - if ($description) {
1687 - $debug['final_description'] = $description;
1688 -
1689 - if ($this->has_thinkrank_metadata() && !empty($this->current_metadata['description'])) {
1690 - $debug['description_source'] = 'post_metadata';
1691 - } elseif ($this->site_identity_data && $this->site_identity_data['enabled']) {
1692 - $settings = $this->site_identity_manager->get_settings('site');
1693 - if (!empty($settings['default_meta_description'])) {
1694 - $debug['description_source'] = 'site_identity_default';
1695 - } else {
1696 - $debug['description_source'] = 'auto_generated';
1697 - }
1698 - } else {
1699 - $debug['description_source'] = 'auto_generated_or_site_description';
1700 - }
1701 - } else {
1702 - $debug['description_source'] = 'none';
1703 - }
1704 -
1705 - return $debug;
1706 - }
1707 -
1708 - /**
1709 4341 * Get Twitter image with proper fallback priority
1710 4342 *
1711 4343 * @since 1.0.0
1712 4344 *
@@ -1712,13 +4344,18 @@
1712 4344 *
1713 4345 * @return string|null Twitter image URL or null if none available
1714 4346 */
1715 4347 private function get_twitter_image_with_fallback(): ?string {
1716 - // For posts, check for post-specific Twitter image meta first (future enhancement)
4348 + // Cascade: post-specific Twitter image > post-specific OG image > featured image.
1717 4349 if (is_singular() && $this->current_post_id) {
1718 4350 $post_twitter_image = get_post_meta($this->current_post_id, '_thinkrank_twitter_image', true);
1719 4351 if (!empty($post_twitter_image)) {
1720 4352 return $post_twitter_image;
4353 + }
4354 +
4355 + $post_og_image = get_post_meta($this->current_post_id, '_thinkrank_og_image', true);
4356 + if (!empty($post_og_image)) {
4357 + return $post_og_image;
1721 4358 }
1722 4359
1723 4360 // Check featured image as fallback for posts
1724 4361 if (has_post_thumbnail($this->current_post_id)) {